HashMap的构造函数
综述
hashmap是一个数组+链表+红黑树组成的数据结构,数组索引为key的hash值的对应位置,而hash值重复的元素,在元素数量小于8的时候,数据结构为链表,在元素大于8的时候,数据结果为红黑树,因为红黑树的搜索时间复杂度为logn,而链表的搜索时间复杂度为n/2。
1. 默认构造函数
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
使用默认的参数,既使用 0.75 的扩容因子,16的初始容量创建一个空的HashMap.
2. 指定初始容量和扩容因子的构造函数
public HashMap(int initialCapacity, float loadFactor) {
//初始容量不能小于0
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
//默认最大容量为 1<<30 既2的30次方,如果大于此数据,则设为最大容量
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);
}
2.1 tableSizeFor()方法
- 因为HashTable的容量都为2的幂次方,所以这个方法核心就是将初始容量处理,得到比2的幂次方小或相等的数值,并且这个值不能大于最大容量。
- 因为2的幂次方书都为,1为最高为,其他位都为0,所以这个这个方法的核心是让某数的二进制的所有位都变为1,这样在其最后结果加1就得到了恰好可以覆盖初始容量的值,而在前面减去1是为了防止其恰好为2的幂次方。
//map的最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 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;
}
比如:输入5
0101 => 0010 | 0101 => 0111
0111+1=7+1 =8
3.HashMap的put()方法
3.1 put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
3.2 hash(key)方法
- 在其本身的hash值基础上,将其本身的hash值向右移动16位,与本身的hash值做异或运算,既高16位不变,第16位做异或计算。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
3.2 putVal()方法
- onlyIfAbsent 参数位true的时候,则不改变现有值
- evict 表处于创建模式,不明白
- 当table数组为空或者table数组大小为0的时候,执行resize()方法;
/**
* 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;
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) // -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;
}
3.3 resize()方法
- 作用:初始化或者加倍table的容量,如果为空,则使用threshold(构造函数中可以设置)字段存储的值进行初始化。如果表不为null,由于我们使用2的幂来扩容,则每个bin元素要么还是在原来的bucket中,要么在2的幂中。
- 过程:
/**
* 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;
//如果老的table容量大于0
if (oldCap > 0) {
//如果老的大于等于HashMap最大允许容量,则直接threshold设为最大int数,直接返回老的table,
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//如果扩容后的cap值比最大容量小,并且老的cap值大于16,则可以将threshold值也同样扩大2倍
//因为threshold=capacity*loadFactor
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;
}
参考:
文 | 地址 |
---|---|
map容量为何是1<<30 | https://blog.csdn.net/qq_33666602/article/details/80139620 |
map的tableSizeFor方法 | https://blog.csdn.net/fan2012huan/article/details/51097331 |
网友评论