JAVA基础总结(五) ----MAP集合类
一、HashMap实现类
java.util.HashMap<K,V>
- 底层是哈希表
- 无序集合
注意:在存储自定义类必须重写hashCode和equals方法保证Key唯一
二、LinkedHashMap实现类
java.util.LinkedHashMap<K,V>
- 底层是链表+哈希表
- 有序集合
三、Map集合类常用方法
public V put(K key,V value): 将指定的键值对儿添加到Map集合中,并返回被替换的value值
Map<String,String> map = new HashMap<>();
String value = map.put("a","1"); //返回null
String value2 = map.put("b","2"); //返回1
public V remove(Object key): 将指定的值对应的元素删除,并返回被删除的value值
String value3 = map.remove("a");//返回1
String value4 = map.remove("4");//返回 null
public V get(Object key): 返回对应key的value值,不存在返回null
String value5 = map.get("a");//返回 1
String value6 = map.get("23");//返回 null
boolean containsKey(Object key):判断是否存在指定的键值对儿
boolean b = map.containsKey("a"); //返回true
boolean b2 = map.containsKey("c"); //返回false
四、Map集合类遍历方法
使用keySet方法遍历
for(String key : map.keySet){
String key = it.next();
String value = map.get(key);
}
使用entraySet方法遍历
for(Map.Entry<String,String> entry : map.entrySet()){
entry.getValue();
entry.getKey();
}
五、treeMap集合类
内部存储按照key的排序进行存储
六、比较
Hashtable | HashMap |
---|---|
可以空值空键 | 不可以空值空键 |
线程不安全 | 线程安全 |