1.map集合中有 建 ,建头有个对应的值(映射),数据结构
一个映射不能包含重复的键spa
每一个键最多只能映射到一个值code
2.Map和Collection接口的不一样,对象
map是双列集合,Collection是单列集合blog
Map的键是惟一,Collection的子系Set是惟一的排序
Map集合的数据结构只针对键有效 接口
3.当集合中建重复时,对应的值取到的内容是最后一次添加进去的内容rem
1 //返回值被覆盖的内容 2 //第一次添加值时,集合中没有数据,被覆盖的内容为null,因此返回null 3 Map<String, Integer> map = new HashMap<>(); 4 map.put("a", 1); 5 map.put("a", 3); //此时输出,返回值是1 6 map.put("f", 4); 7 map.put("t", 2); 8 System.out.println(map);//输出结果为 {a=3, t=2, f=4} 9 map.size(); //长度 10 map.remove("a"); //删除指定键,与映射值 11 map.containsKey("a"); //是否包含键为"a"的的内容 12 map.containsValue(2); //是否包含值为2的内容 13 map.clear(); //清空 14 map.isEmpty(); //是否为空 15 16 }
3.Map的遍历get
第一种hash
1 /* 2 * 1,首先得到到map中全部键, 3 * 2.在经过键得到对应的内容 4 */ 5 Map<String, Integer> map = new HashMap<>(); 6 map.put("a", 1); 7 map.put("a", 3); //此时输出,返回值是1 8 map.put("f", 4); 9 map.put("t", 2); 10 11 /* 12 * 先把键都添加到set集合中, 13 * 在使用set集合的迭代器, 14 * 经过get方法,在获取对应的值 15 */ 16 Set<String> set = map.keySet(); 17 Iterator<String> it = set.iterator(); 18 while(it.hasNext()) { 19 String s = it.next(); 20 Integer a = map.get(s); 21 System.out.println(a+ " "); 22 }
第二种遍历方式
1 HashMap<String, Integer> map = new HashMap<>(); 2 map.put("a", 1); 3 map.put("a", 3); // 此时输出,返回值是1 4 map.put("f", 4); 5 map.put("t", 2); 6 // 获取键值对对象 7 Set<Map.Entry<String, Integer>> set = map.entrySet(); 8 // 迭代器 9 Iterator<Map.Entry<String, Integer>> it = set.iterator(); 10 while (it.hasNext()) { 11 // 获取到每一个键值对对象 12 Map.Entry<String, Integer> en = it.next(); 13 String s = en.getKey(); 14 Integer i = en.getValue(); 15 System.out.println(s + " " + i); 16 }
第三种
缺点不能删除
1 for (Map.Entry<String, Integer> entry : set) { 2 System.out.println(entry.getKey() + " " + entry.getValue()); 3 }
用加强for循环遍历
须要重写hashcode,和equals方法
保证怎么存怎么取的集合
排序去重复 treeset和treemap的功能是同样的
遍历自定义对象时,要记得Comparable