Java HashMap源码解读
目前网上关于jdk hashmap源码解读的文章已经有很多,而写该博客的主要是为了记录自己对于源码学习过程,期间参考了许多其他优秀博客的理
分析思路
实现结构
extends AbstractMap<K ,V> implements Map <K ,V>, Cloneable, Serializable
数据结构
数组+链表+红黑树 hashmap 底层的数组称为哈希桶,每个桶里放的是链表,当链表长度大于8会转变为红黑树,目的是为了提高插入与查询的效率 由于底层是数组实现,当插入的元素达到一定数量是会进行扩容操作,变为原来的两倍 我们可以将hashmap理解为了一个桶
进入正题
有了桶这个概念后我们将对以下几个属性进行理解
capacity 桶的容量 这个桶能装多少东西size 桶已经装了多少东西loadFactory 负载因子 衡量桶是否应该扩容的标准 hashmap默认值0.75f,一般不去改threshold capacity*loadFactory 当size>threhold时进行扩容,扩容是容量翻倍,所以原链表上的每个节点,现在可能存放在原来的下标,即low位, 或者扩容后的下标,即high位。 high位= low位+原哈希桶容量 链表节点Node
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; 节点的hash值
final K key; key值
V value ; value 值
Node<K,V> next;
Node(int hash, K key, V value , Node<K,V> next) {
this .hash = hash;
this .key = key;
this .value = value ;
this .next = next;
}
public final K getKey () { return key; }
public final V getValue () { return value ; }
public final String toString () { return key + "=" + value ; }
public final int hashCode () {
return Objects.hashCode(key) ^ Objects.hashCode(value );
}
public final V setValue (V newValue) {
V oldValue = value ;
value = newValue;
return oldValue;
}
public final boolean equals (Object o) {
if (o == this )
return true ;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value , e.getValue()))
return true ;
}
return false ;
}
}
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4 ;
static final int MAXIMUM_CAPACITY = 1 << 30 ;
static final float DEFAULT_LOAD_FACTOR = 0.75 f;
public HashMap (int initialCapacity) {
this (initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap () {
this .loadFactor = DEFAULT_LOAD_FACTOR;
}
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);
}
static final int tableSizeFor(int cap) {
int n = cap - 1 ;
n |= n >>> 1 ;
n |= n >>> 2 ;
n |= n >>> 4 ;
n |= n >>> 8 ;
n |= n >>> 16 ;
return (n < 0 ) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1 ;
}
public void putAll (Map<? extends K, ? extends V> m) {
putMapEntries(m, true );
}
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0 ) {
if (table == null ) {
float ft = ((float )s / loadFactor) + 1.0 F;
int t = ((ft < (float )MAXIMUM_CAPACITY) ?
(int )ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold)
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value , false , evict);
}
}
}
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null ) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0 ;
if (oldCap > 0 ) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1 ) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1 ;
}
else if (oldThr > 0 )
newCap = oldThr;
else {
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int )(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0 ) {
float ft = (float )newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float )MAXIMUM_CAPACITY ?
(int )ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings ({"rawtypes" ,"unchecked" })
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null ) {
for (int j = 0 ; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null ) {
oldTab[j] = null ;
if (e.next == null )
newTab[e.hash & (newCap - 1 )] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this , newTab, j, oldCap);
else {
Node<K,V> loHead = null , loTail = null ;
Node<K,V> hiHead = null , hiTail = null ;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0 ) {
if (loTail == null )
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null )
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null );
if (loTail != null ) {
loTail.next = null ;
newTab[j] = loHead;
}
if (hiTail != null ) {
hiTail.next = null ;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
public V put (K key, V value ) {
return putVal(hash(key), key, value , false , true );
}
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 ;
}
static final int hash(Object key) {
int h;
return (key == null ) ? 0 : (h = key.hashCode()) ^ (h >>> 16 );
}
public V remove (Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null , false , true )) == null ?
null : e.value ;
}
final Node<K,V> removeNode(int hash, Object key, Object value ,boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1 ) & hash]) != null ) {
Node<K,V> node = null , e; K k; V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null ) {
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break ;
}
p = e;
} while ((e = e.next) != null );
}
}
if (node != null && (!matchValue || (v = node.value ) == value ||(value != null && value .equals(v)))) {
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this , tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null ;
}
public V get (Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value ;
}
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 ;
}
public boolean containsKey (Object key) {
return getNode(hash(key), key) != null ;
}
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 ;
}
public boolean containsValue (Object value ) {
Node<K,V>[] tab; V v;
遍历hash桶 找到value 返回true
if ((tab = table) != null && size > 0 ) {
for (int i = 0 ; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null ; e = e.next) {
if ((v = e.value ) == value ||
(value != null && value .equals(v)))
return true ;
}
}
}
return false ;
}
getOrDefault() 没有查到就返回默认值
@Override
public V getOrDefault (Object key, V defaultValue) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? defaultValue : e.value ;
}
hashmap与其他类的对比
与hashtable的对比
1.HashTable的方法是同步的,在方法的前面都有synchronized 来同步,HashMap未经同步,所以在多线程场合要手动同步 2.HashTable不允许null值(key和value都不可以) ,HashMap允许null值(key和value都可以)。 3.HashTable有一个contains(Object value)功能和containsValue(Object value)功能一样。 4.HashTable使用Enumeration进行遍历,HashMap使用Iterator进行遍历。 5.HashTable中hash数组默认大小是11,增加的方式是 old*2+1。HashMap中hash数组的默认大小是16,而且一定是2的指数。 6.哈希值的使用不同,HashTable直接使用对象的hashCode,hashmap高低位参与运算 与hashSet的对比
public HashSet () {
map = new HashMap<E,Object>();
}
调用HashSet的add方法时,实际上是向HashMap中增加了一行(key-value对),该行的key就是向HashSet增加的那个对象,该行的value就是一个Object类型的常量 与concurrentHashmap