java.util.Map
接口是JDK1.2开始提供的一个基于键值对的散列表接口,其设计的初衷是为了替换JDK1.0中的java.util.Dictionary
抽象类。Dictionary是JDK最初的键值对类,它不可以存储null作为key和value,目前这个类早已不被使用了。目前都是在使用Map接口,它是可以存储null值作为key和value,但Map的key是不可以重复的。其常用的实现类主要有HashMap,TreeMap,ConcurrentHashMap等
HashMap源码解读
目前JDK已经发布到JDK12,主流的JDK版本是JDK8, 但是如果阅读HashMap的源码建议先看JDK7的源码。JDK7和JDK8的源码中HashMap的实现原理大体相同,只不过是在JDK8中做了部分优化。但是JDK8的源码可读性非常差。
HashMap 是一个存储键值对(key-value)映射的散列表,继承于AbstractMap,实现了Map、Cloneable、java.io.Serializable接口,HashMap是线程不安全的,它存储的映射也是无序的。
HashMap的底层主要是基于数组和链表来实现的(JDK8之后又引入了红黑树),数据存储时会通过对key进行哈希操作取到哈希值,然后将哈希值对数组长度取模,得到的值就是该键值对在数组中的索引index值,如果数组该位置没有值则直接将该键值对放在该位置,如果该位置已经有值则将其插入相应链表的位置,JDK8开始为优化链表长度过长导致的性能问题从而引入了红黑树,当链表的长度大于8时会自动将链表转成红黑树。
JDK7中HashMap的源码解读
JDK7中HashMap采用Entry数组来存储键值对,每一个键值对组成了一个Entry实体,Entry类实际上是一个单向的链表结构,它具有Next指针,可以连接下一个Entry实体组成链表。
JDK7中HashMap源码中的主要字段
// 数组默认的大小
// 1 << 4,表示1,左移4位,变成10000,即16,以二进制形式运行,效率更高
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 数组最大值
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默认的负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 真正存放数据的数组
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
HashMap中默认的数组容量为 16,负载因子为 0.75。Map 在使用过程中不断的往里面存放数据,当数量达到了 16 * 0.75 = 12 就需要将当前 16 的容量进行扩容,而扩容这个过程涉及到 rehash、复制数据等操作,所以非常消耗性能。因此通常建议能提前预估 HashMap 的大小最好,尽量的减少扩容带来的性能损耗。
JDK7中HashMap源码中的构造器
/** 默认的初始化容量、默认的加载因子
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() { //16 0.75
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity.
* @throws IllegalArgumentException if the initial capacity is negative.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/** 做了两件事:1、为threshold、loadFactor赋值 2、调用init()
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY) //限制最大容量
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor)) //检查 loadFactor
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
//真正在做的,只是记录下loadFactor、initialCpacity的值
this.loadFactor = loadFactor; //记录下loadFactor
threshold = initialCapacity; //初始的 阈值threshold=initialCapacity=16
init();
}
/**
* Constructs a new <tt>HashMap</tt> with the same mappings as the
* specified <tt>Map</tt>. The <tt>HashMap</tt> is created with
* default load factor (0.75) and an initial capacity sufficient to
* hold the mappings in the specified <tt>Map</tt>.
*
* @param m the map whose mappings are to be placed in this map
* @throws NullPointerException if the specified map is null
*/
public HashMap(Map<? extends K, ? extends V> m) {
this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
inflateTable(threshold);
putAllForCreate(m);
}
JDK7中HashMap源码中的put方法
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold); //初始化表 (初始化、扩容 合并为了一个方法)
}
if (key == null) //对key为null做特殊处理
return putForNullKey(value);
int hash = hash(key); //计算hash值
int i = indexFor(hash, table.length); //根据hash值计算出index下标
for (Entry<K,V> e = table[i]; e != null; e = e.next) { //遍历下标为i处的链表
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { //如果key值相同,覆盖旧值,返回新值
V oldValue = e.value;
e.value = value; //新值 覆盖 旧值
e.recordAccess(this); //do nothing
return oldValue; //返回旧值
}
}
modCount++; //修改次数+1,类似于一个version number
addEntry(hash, key, value, i);
return null;
}
/**
* Adds a new entry with the specified key, value and hash code to
* the specified bucket. It is the responsibility of this
* method to resize the table if appropriate.
*
* Subclass overrides this to alter the behavior of put method.
*/
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) { //如果size大于threshold && table在下标为index的地方已经有entry了
resize(2 * table.length); //扩容,将数组长度变为原来两倍
hash = (null != key) ? hash(key) : 0; //重新计算 hash 值
bucketIndex = indexFor(hash, table.length); //重新计算下标
}
createEntry(hash, key, value, bucketIndex); //创建entry
}
/**
* Rehashes the contents of this map into a new array with a
* larger capacity. This method is called automatically when the
* number of keys in this map reaches its threshold.
*
* If current capacity is MAXIMUM_CAPACITY, this method does not
* resize the map, but sets threshold to Integer.MAX_VALUE.
* This has the effect of preventing future calls.
*
* @param newCapacity the new capacity, MUST be a power of two;
* must be greater than current capacity unless current
* capacity is MAXIMUM_CAPACITY (in which case value
* is irrelevant).
*/
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) { //状态检查
threshold = Integer.MAX_VALUE;
return;
}
Entry[] newTable = new Entry[newCapacity]; //实例化新的table
transfer(newTable, initHashSeedAsNeeded(newCapacity)); //赋值数组元素到新的数组
table = newTable;
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
/**
* Transfers all entries from current table to newTable.
*/
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry<K,V> e : table) {
while(null != e) {
Entry<K,V> next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key); //对key进行hash
}
int i = indexFor(e.hash, newCapacity); //用新的index来取模
e.next = newTable[i];
newTable[i] = e; //把元素存入新table新的新的index处
e = next;
}
}
}
/**
* Like addEntry except that this version is used when creating entries
* as part of Map construction or "pseudo-construction" (cloning,
* deserialization). This version needn't worry about resizing the table.
*
* Subclass overrides this to alter the behavior of HashMap(Map),
* clone, and readObject.
*/
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex]; //获取table中存的entry
table[bucketIndex] = new Entry<>(hash, key, value, e); //将新的entry放到数组中,next指向旧的table[i]
size++; //修改map中元素个数
}
JDK7中HashMap源码中的put方法
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>A return value of {@code null} does not <i>necessarily</i>