Map接口与实现类
Map体系集合
graph TD;
Interface.Map-->Class.HashMap
Interface.Map-->Interface.SortedMap
Interface.SortedMap-->Class.TreeMap
Interface:接口
Class:实现类
Map接口的特点:
- 用于存储任意键值对(Key-Value)
- 键:无序,无下标,不允许重复(唯一)
- 值:无序,无下标,允许重复
Map父接口
-
特点:存储一对数据(Key-Value),无序,无下标,键不可重复,值可重复
-
Set(Map.Entry<K,V>) 键值匹配的Set集合
-
Collection values() 返回包含所有值的Collection集合
-
方法:
-
V put(K key, V value) 将对象存入到集合中,关联键值。Key重复则覆盖原值
-
Object get(Object key) 根据键获取对应的值
-
Set keySet(K) 返回所有的Key 返回的是一个Key(键)
-
Set<Map.Entry<K,V>> entrySet() 返回集合中包含关系的Set集合 返回的个一个Entry(键值对)
-
package com.jhkj.map;
import java.util.HashMap;
import java.util.Map;
/**
* Map接口的使用
* 特点:
* 1.存储的为键值对
* 2.键不能重复,值可以重复
* 3.无序
*/
public class Demo1 {
public static void main(String[] args) {
// 创建Map对象
Map<String,String> map = new HashMap<>();
// 1.添加数据
map.put("cn","中国");
map.put("uk","英国");
map.put("usa","美国");
System.out.println("元素个数:" + map.size());
System.out.println(map.toString());
// 2.删除数据
map.remove("usa");
System.out.println(map.toString());
// 3.遍历数据
// 3.1使用keySet()
System.out.println("----------使用keySet()----------");
for (String key : map.keySet()) {
System.out.println(key + "-----" + map.get(key));
}
// 3.2使用entrySet()
System.out.println("----------使用entrySet()------------");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "------" + entry.getValue());
}
// 4.判断
// 判断Key是否存在
System.out.println(map.containsKey("cn"));
// 判断Value是否存在
System.out.println(map.containsValue("俄罗斯"));
}
}
Map集合的实现类
- HashMap(重点):
- 存储结构:哈希表(数组+链表+红黑树)
- JDK1.2版本,线程不安全,运行效率快;允许用null 作为key或者value
- Hashtable(了解一下):
- jdk1.0版本,线程安全,允许效率慢;不允许null作为key或是value
- Properties(Hashtable的子类):
- Hashtable的子类,要求key和value都是String。通常用于配置文件的读取
- TreeMap:
- 存储结构:红黑树
- 实现了SortedMap接口(是Map的子接口),可以对key自动排序
HashMap源码分析总结
- HashMap刚创建时,table时null,为了节省空间,当添加第一个元素时,table容量调整为16
- 当元素个数大于阈值(16*0.75=12)时,会进行扩容,扩容后大小为原来的2倍,目的时减少调整元素的个数
- Jdk1.8 当每个链表长度大于8时,并且元素个数大于等于64时,会调整为红黑树,目的提高执行效率
- jdk1.8 当链表长度小于6时,调整成链表
- jdk1.8以前,链表是头插入,jdk1.8以后是尾插入
HashMap 与 HashSet 的关系
- 实际上HashSet实现类中调用的就是HashMap类
public HashSet() {
map = new HashMap<>();
}
add方法调用的就是HashMap中的Key
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
TreeSet 与 TreeMap 的关系
- 实际上TreeSet实现类中调用的就是TreeMap类
public TreeSet() {
this(new TreeMap<E,Object>());
}