public class HashMap <K ,V > extends AbstractMap <K ,V >
implements Map <K ,V >, Cloneable , Serializable
HashMap泛型实现,同时继承自AbstractMap,依赖于AbstractMap的部分方法(如:hashCode、equals方法),实现了Map接口实现了一些Map的接口,其次实现了复制和序列化接口。
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4 ;
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30 ;
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75 f;
transient Node<K,V>[] table;
transient Set<Map.Entry<K,V>> entrySet;
transient int size;
transient int modCount;
着重介绍几个参数:DEFAULT_INITIAL_CAPACITY是默认的初始化空间大小为16,MAXIMUM_CAPACITY是最大的空间大小为1073741824,DEFAULT_LOAD_FACTOR是默认的负载因子为0.75,HashMap底层使用数组保存Node对象,使用Set保存Map.Entry对象用于keySet()、values()方法,使用size记录大小,使用modCount记录HashMap的改变状态同时可以抛出ConcurrentModificationException异常。
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))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this .loadFactor = loadFactor;
this .threshold = tableSizeFor(initialCapacity);
}
这个方法是带有空间大小和负载因子的构造方法,具体实现如上。同时如果是空的构造方法就是默认初始化大小为16,负载因子为0.75。
final V putVal(int hash, K key, V value , boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0 )
n = (tab = resize()).length;
if ((p = tab[i = (n - 1 ) & hash]) == null )
tab[i] = newNode(hash, key, value , null );
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this , tab, hash, key, value );
else {
for (int binCount = 0 ; ; ++binCount) {
if ((e = p.next) == null ) {
p.next = newNode(hash, key, value , null );
if (binCount >= TREEIFY_THRESHOLD - 1 )
treeifyBin(tab, hash);
break ;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break ;
p = e;
}
}
if (e != null ) {
V oldValue = e.value ;
if (!onlyIfAbsent || oldValue == null )
e.value = value ;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null ;
}
好吧,打开一看,这实现怎么和我记忆中的实现一点都不一样呢,原来JDK1.8把HashMap优化了一下。在JDK1.6中,HashMap采用位桶+链表实现,即使用链表处理冲突,同一hash值的链表都存储在一个链表里。但是当位于一个桶中的元素较多,即hash值相等的元素较多时,通过key值依次查找的效率较低。而JDK1.8中,HashMap采用位桶+链表+红黑树实现,当链表长度超过阈值(8)时,将链表转换为红黑树,这样大大减少了查找时间。
方法的意义是判断键值对数组tab[]是否为空或为null,否则resize();根据键值key计算hash值得到插入的数组索引i,如果tab[i]==null,直接新建节点添加,否则转入判断当前数组中处理hash冲突的方式为链表还是红黑树(check第一个节点类型即可),分别处理。
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1 ) & hash]) != null ) {
if (first.hash == hash &&
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null ) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null );
}
}
return null ;
}
该方法为get方法实际调用的方法,其通过hash寻址,然后根据第一个结点的类型去对链表查询或者对红黑树查询,这样的查询效率显著提高。