人狠话不多,菜就完了!
public static void main(String[] args) {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("1", "A");
hashMap.put("1", "B");
hashMap.put("2", "C");
System.out.println(hashMap.get("1"));
}
HashMap中定义的默认参数
//默认数组大小为16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//最大数组大小
static final int MAXIMUM_CAPACITY = 1 << 30;
//扩容因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//当数组某个桶的标挂载的是红黑树且节点小于6时,转为链表
static final int UNTREEIFY_THRESHOLD = 6;
//当数组某个桶的坐标挂载的是链表且节点大于8,数组大小大于64时转为红黑树,
//如果数组大小不大于64时将进行扩容,而不是转为红黑树
static final int TREEIFY_THRESHOLD = 8;
static final int MIN_TREEIFY_CAPACITY = 64;
HashMap中提供的构造函数:源码中提供了4种构造函数,我们可以看到前3种构造函数没有一个在new时对hashmap初始化,第4种构造如果传入的map的size > 0则会被初始化,否则不会初始化
//带数组大小和扩容因子的构造函数
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);
}
//带数组大小的构造函数
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
//空参构造函数
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
//构造函数中传入Map对象
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
hashMap.put(“1”, “A”);
hashMap.put(“1”, “B”);
//调用put方法时首先计算key的hash值
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//如果key为空时,hash值返回0,说明key为空的值都存储在数组索引为0 的位置上
//h = key.hashCode()) ^ (h >>> 16) key值计算hashCode值后与自身左移16位后的值进行异或运算,
//这是为了让计算hashCode值的后16位也参与到hash的计算中,降低hash碰撞的概率,既扰动函数
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
* 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;
//如果hashMap还没有初始化,将调用resize()进行初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//如果初始化后的数组tab,下标为(n - 1) & hash是空的,
//说明该桶的坐标上没有值,直接将数据放在该桶的坐标上
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//该桶的坐标上已经有值
else {
Node<K,V> e; K k;
//如果该桶的坐标上第一个数据的hash值和put进来的key的hash值相等,
//并且key非空且相等,说明是同一个key(覆盖)
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//key不相等,需要遍历该桶的坐标上的所有数据,分为红黑树和链表结构
//红黑树结构
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) {
//将put进来的数据插入尾部(尾插法,JDK1.7是头插法)
p.next = newNode(hash, key, value, null);
//如果节点数大于等于8,需要树化,转红黑树(因为菜,所以搞不懂红黑树)
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//如果key是同一个key,跳出循环
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;
//!onlyIfAbsent = true
if (!onlyIfAbsent || oldValue == null)
e.value = value;
//空方法,留给LinkedHashMap使用
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//是否需要扩容
if (++size > threshold)
resize();
//空方法,留给LinkedHashMap使用
afterNodeInsertion(evict);
return null;
}
在putval方法中将对hashMap完成初始化或扩容,具体由resize()方法实现
final Node<K,V>[] resize() {
//记录旧的数组
Node<K,V>[] oldTab = table;
//根据oldCap的大小决定是初始化还是扩容
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//旧是扩容阈值,即capacity * load factor 数组大小 X 扩容因子
int oldThr = threshold;
int newCap, newThr = 0;
//如果是扩容,判断是否还能扩容
if (oldCap > 0) {
//数组已经是最大值,1 <<< 30 将扩容的阈值设为Integer.MAX_VALUE(远远大于1 <<< 30)
//将永远无法触发扩容,并返回旧的数组
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//如果数组还未到达最大值,新数组的大小是原数组大小 X 2。
//如果新数组的大小size < 1 <<< 30 并且旧数组的大小size >= 16(像new HashMap(4)
//这种创建方法,数组大小会小于默认值16),扩容的阈值也是原阈值 X 2
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
//如果是初始化并且扩容的阈值大于0
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
//数组大小为16,扩容阈值为16 X 0.75 = 12
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;
//oldTab != null 是扩容操作,需要将旧数组上的数组遍历到新的数组上
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;
}
hashMap.get(“1”)
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;
//数组被初始化并已经有值,hash对应的桶的坐标存在值
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//第一个节点的key就是get的key
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//对应桶的坐标上有2个以上节点
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;
}
总结
1、初始化时数组的大小一定是2的幂次(每次扩容都是原size X 2)
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);
}
//按位或运算 3 |= 3 >>> 1 即 0011 | 0001 = 0011 = 3 只有都是0的时候结果才是0
//return 3 + 1
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、为什么数组大小必须是2的幂次方
i = (n - 1) & hash
a)在确定key在数组中的位置时,进行了&运算。如果能保证数组大小是2的幂次方,那么 转化成2进制时,最低的几位都是1。如 2 - 1 = 0001、4 - 1 = 0011、8 - 1 = 0111、16 - 1 = 1111等等。在进行&运算时(只有都为1时结果才为1)。如 0101 & 1111 = 0101,能够确保&运算的值始终小于数组的大小(如果数组大小是24:24 - 1 & 32 即 0001 0111 & 0001 1111 = 0001 0111 = 24 ,而数组最大索引为24 - 1 = 23)。
b)数组在扩容后(原数组size X 2),元素所在的桶的坐标不变或原来的桶的坐标+ size:0000 1111 & 0001 1111 = 0000 1111 扩容后 0001 1111 & 0001 1111 = 0001 1111。
3、怎么确保散列尽可能均匀的分散在数组中
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
在对key进行hash运算时,对key的hashCode值与自身右移16后进行异或运算,让hashCode值的高位也参与进来。
4、HashMap为什么是线程不安全的
DK1.7中,并发执行扩容操作时会造成环形链和数据丢失的情况,JDK1.8将插入数据时的头插法改为尾插法,解决了死循环的问题,但还是会出现数据覆盖的问题。putVal方法中if ((p = tab[i = (n - 1) & hash]) == null)在并发时发生hash碰撞会产生数据覆盖。if (++size > threshold) ++操作也是线程不安全的,会少计算。