Map
-
双列集合 Key,value
-
以"键/值"对存放元素
-
键值(Key)不可重复,值(value)可重复
-
一般把键值对称为映射
HashMap
-
键值不能重复,并且无序,可以键和值都可以存放null值
-
线程不安全
-
底层结构跟HashSet一样
put(K Ket,V value)
添加到集合中的键值对,如果有重复元素则会覆盖原有元素
HashMap<String,String> hm = new HashMap<String, String>();
hm.put("aa", "123");
hm.put("bb", "456");
hm.put("cc", "789");
System.out.println(hm);//结果为{aa=123, bb=456, cc=789}
get(Object key)
根据Key获取value,如果不存在则返回null
HashMap<String,String> hm = new HashMap<String, String>();
hm.put("aa", "123");
hm.put("bb", "456");
hm.put("cc", "789");
String string = hm.get("aa");
String str = hm.get("dd");
System.out.println(string);//123
System.out.println(str);//null
remove(Object Key)
根据Key删除指定元素
HashMap<String,String> hm = new HashMap<String, String>();
hm.put("aa", "123");
hm.put("bb", "456");
hm.put("cc", "789");
hm.remove("aa");
System.out.println(hm);//结果为{bb=456, cc=789}
遍历Map集合
1.先把Map中的Key取出,取出后是一个Set集合
HashMap<String,String> hm = new HashMap<String, String>();
hm.put("aa", "123");
hm.put("bb", "456");
hm.put("cc", "789");
Set<String> keySet = hm.keySet();
for (String Key : keySet) {
System.out.println(hm.get(Key));//结果为123 456 789
}
2.使用entrySet(),其中Entry是java中专门用来保存映射(Key,value)的对象
HashMap<String,String> hm = new HashMap<String, String>();
hm.put("aa", "123");
hm.put("bb", "456");
hm.put("cc", "789");
Set<Entry<String, String>> entrySet = hm.entrySet();
for (Entry<String, String> entry : entrySet) {
System.out.print(entry.getKey()+":"+entry.getValue()+" ");//结果为aa:123 bb:456 cc:789
}
TreeMap
-
按照键值来排序,线程不安全
-
底层是二叉树结构,根据Key来排序的
-
底层结构跟TreeSet一样
-
TreeSet是TreeMap集合Key值的结构
-
键值不能为null,value可以为null
-
能自动排序
单列结构的底层是双列结构,把TreeMap的Key拿出来给TreeSet,然后value全是null,就实现了单列变成了双列
不能实现Comparable接口,只能把集合变成可比较性
Hashtable
-
Key和value都不能为null
-
线程安全
-
能自动排序
-
底层结构只有哈希表的一半,是数组