Map和List一样,是一种最基础的数据结构,它描述的是一个key和一个value一一对应的数据结构。每种高级语言都有对Map的定义和实现
- 源码中Map接口中常用的有put、getKey()、getValue()、containsKey()
- HashMap实现了接口Map
- key键是不会重复的,value可重复
- 键值对是没有顺序的,实验结果如下:
key为key40,value为0.39682183038360286
key为key44,value为0.5142990864701991
key为key43,value为0.01583874506941041
key为key42,value为0.17293650440621833
package com.geekbang;
import java.util.HashMap;
import java.util.Map;
public class LearnMapAppMain {
public static void main(String[] args) {
Map<String, String> map = createMap(3);
System.out.println(map.get("key2"));
System.out.println(map.get(new Object()));
System.out.println(map.get("Key99"));
//删除key
String keyToRemove = "key1";
System.out.println(keyToRemove+"对应的值为:"+map.get(keyToRemove));
map.remove(keyToRemove);
System.out.println(keyToRemove+"对应的值为:"+map.get(keyToRemove));
//遍历key和value
for(Map.Entry<String, String> entry:map.entrySet()) {
System.out.println("key为"+entry.getKey()+",value为"+entry.getValue());
}
//遍历key
for(String key:map.keySet()) {
System.out.println(key);
}
//遍历value
for(String values:map.values()) {
System.out.println(values);
}
}
private static Map<String, String> createMap(int size){
Map<String, String> retMap = new HashMap<String, String>();
for(int i=0;i<size;i++) {
retMap.put("key"+i, String.valueOf(Math.random()));
}
return retMap;
}
}
打印结果:
0.44727281641631766
null
null
key1对应的值为:0.9820494889599133
key1对应的值为:null
key为key2,value为0.44727281641631766
key为key0,value为0.6133368241101768
key2
key0
0.44727281641631766
0.6133368241101768