Map的结构如下:
Map的特点:
- Map是一个双列集合,元素由键值对构成(key–value)
- key值不可以重复,value可以重复
- 一个key只能对应一个value,而多个不同的key可以对应同一个value
- 访问key可以直接获得value
- key–value可以是相同或不同的数据类型,但是不允许Map包含自己作为键。虽然允许Map包含自己作为一个值,但建议要特别小心:在这样的Map上,equals和hashCode方法不再被很好地定义。
- 没有继承Collection接口
声明:
1 Map<Integer,Integer> map=new HashMap<Integer,Integer>();
遍历方法(以HashMap举例):
- 使用迭代器遍历
Map<Integer, Integer> map = new HashMap<>();
map.put(1, 2);
map.put(2, 3);
map.put(3, 4);
map.put(4, 5);
Iterator item = map.keySet().iterator();
while (item.hasNext()) {
Object key = item.next();
System.out.println(key + ":" + map.get(key));
}
- 使用foreach遍历
Map<Integer, Integer> map = new HashMap<>();
map.put(1, 2);
map.put(2, 3);
map.put(3, 4);
map.put(4, 5);
for (Integer key : map.keySet()) {
System.out.println(key + ":" + map.get(key));
}