hashmap是一个Node的数组,以下为源代码分析: 数组大小是而2的幂,初始大小16:
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
复制代码
如果传入的构造参数不是2的幂,以下方法取该数字的下一个2的幂。通过无符号右移和或运算,让每一个二进制位都变成1,
/**
* Returns a power of two size for the given target capacity.
*/
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;
}
复制代码
数组长度为2的幂的优点:
- 1.hash效率高。 put阶段,要判断该node放到数组的哪个桶里,采用的方式是table[(n-1)&hash(key)],n是2的幂,n-1的二进制位上全部是1,这样和hash值位与运算,可以更高效率的求出该hash值对应的数组下标。
- 2.resize效率高。(具体代码实现在hashmap.resize()中,)resize阶段,扩容2倍,数组大小n的二进制位数增加1,在rehash的时候,hash值得最高位是0,那么该node不需要移动。只要在hash值最高位是1的时候,rehash的值才会发生变化,而且是增加2的n-1次方。这样扩容的效率更高。
/**
* Computes key.hashCode() and spreads (XORs) higher bits of hash
* to lower. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
复制代码
hash(Object key)方法是对key求hash哈希值,比直接用hashcode更好,因为h无符号右移16位后得到高位,
V Get(Object key)方法
通过getNode(hash(key), key)获得。代码逻辑:
final Node<K,V> getNode(int hash, Object key) {
//数组tab,首节点first,数组大小n,
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//三个条件判断,&&具有短路功能,注意先后顺序。
//1.数组非空,2.数组长度大于零,3,node节点非空.or 直接return null;
if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
//判断是否是first:hash值是否相同&& key引用相同或者equals.(k)
if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
//判断是红黑树or链表
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;
}
复制代码
map的key可以是null
以上get代码可以发现,如果key是null,hash(null)=0,固定在数组的0下标处。null==null位true。
put(key,value)
使用如下方法:
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//如果数组为空,则通过resize()初始化数组。
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 数组里面,还没有node对象则新建;否则新建Node对象插入该Node。
//插入桶,分为两种情况,一种是红黑树。一种是链表。
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) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
复制代码
以上代码用的重要方法为resize,treeifyBin。以下为源代码:
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
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; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
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 { // preserve order
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;
}
复制代码
还有个treeifyBin方法,把该桶里面的单项链表转换为双向链表,然后再转换为红黑树。关于红黑树的具体实现,这边文章先不分析。
remove方法
用到的final Node<K,V> removeNode方法是final,不能被子类重写,只能重新afterNodeRemoval方法来增加逻辑。 removeNode源代码主要考虑了单节点, 链表和树三种情况,主要逻辑是(每一步都要考虑三种情况):
- 1,先找到key这个节点,
- 2,然后再删除这个节点。
keys() values(),entrySet()都提供了一个该hashmap的窗口。
computeIfAbsent
java8之前。从map中根据key获取value操作可能会有下面的操作
Object key = map.get("key");
if (key == null) {
key = new Object();
map.put("key", key);
}
java8之后。上面的操作可以简化为一行,若key对应的value为空,会将第二个参数的返回值存入并返回
Object key2 = map.computeIfAbsent("key", k -> new Object());
复制代码