一.结构
HashMap由数组加链表组成。
Map<Object, Object> hashMap2 = new HashMap<>(); hashMap2.put(key, value);
点put方法查看源码
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }
put方法调用了putVal();参数的各个含义
- hash(key) hash算法算出值用于决定key-value在数组中存放的位置。
- key值。
- value值。
- 我感觉他是和LinkHashMap有关的。
- 同样是和linkHashMap有关。
putVal(hash(key), key, value, false, true);
一个元素put到HashMap中需要算出它的hash值,也就是在数组中位置。
可以看出对于hash算法有三个要求:
- 返回值类型为int。
- 要在数组的范围内,例如HashMap的数组初始化大小为16。也就是算出的值要在0-15之间。
- 要求散列,也就是说尽可能的使计算出的结果值“唯一”。
怎么能满足上述要求呢?
对返回值类型与范围要求保证。
要知道每个Object中会有一个hashCode(),方法通过这个方法能取到这个key的hash值。把这个值&上(n-1),n代表这个数组的长度。假如是16,那么它的二进制为10000减1为01111。把它&上key的hash值也就是算出的最大值为15。
懂吧?
这种方法就保证了算出的值保证了前两条要求。
对于散列性的要求保证。
static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
将key的hash值高16位于低16位取^,这样就能保证了。具体我也看不懂,对不起数学老师(想了解可以去百度)。
假如发生hash碰撞怎么办?
这时候需要链表了。
transient Node<K,V>[] table;// 使用transient修饰的属性是不会被序列化的。
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) // 如果HashMap没经过初始化 n = (tab = resize()).length;// 初始化HashMap,算出扩容阀值大小等信息添加元素后新的数组长度。(有可能不变、有可能扩容)
if ((p = tab[i = (n - 1) & hash]) == null) // 根据hash算法算出数组中位置为null,存入key value 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))))// 如果新添加hash、key等同原来元素那就更新这个元素的值 e = p; else if (p instanceof TreeNode)// 如果链表长度超过8,就会将链表转换为红黑树。判断链表类型是否为红黑树,如果是就像树中添加新节点。 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; }
/** 这个方法将数组进行扩容和将元素添加到数组中 * 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; // 在初始化map大小中默认为16乘以默认负载因子0.75这个值赋给了threshold,成为了扩容阀值12 你可以指定初始化大小和负载因子。 int newCap, newThr = 0; if (oldCap > 0) {// 如果原来数组有数据 if (oldCap >= MAXIMUM_CAPACITY) {// MAXIMUM_CAPACITY表示HashMap数组的最大容量 1《30。如果原来数组已经大于这个长度了 那就给这个数组设置为最大长度。0x7fffffff;也就是int的最大值。 threshold = Integer.MAX_VALUE; return oldTab; } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&// 如果老数组长度左移1位小于数组最大值并且老数组长度大于等于默认长度16 oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold // 新的数组扩容阀值大小为老数组的阀值左移一位。例如12长度左移一个位为24长度。
} else if (oldThr > 0) // initial capacity was placed in threshold// 如果老阀值大于0 newCap = oldThr; // 将老阀值赋给新的数组长度。 else { // zero initial threshold signifies using defaults // 否则数组设置长度、默认扩容阀值12。 newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } if (newThr == 0) { // 如果新数组阀值为0,数组长度*传入的扩容负载因子得出阀值小于int最大值并且数组长度小于int最大长度。就将得出阀值赋给新数组,否则赋给新数组的扩容阀值为int最大值。 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)// 链表下一个元素为null newTab[e.hash & (newCap - 1)] = e; // 将新元素根据hash算法得出元素在数组中下标。 else if (e instanceof TreeNode) //如果链表长度超过8,就会将链表转换为红黑树。判断链表类型是否为红黑树,如果是就像树中添加新节点。
((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; }
链表源码:可以看出是一个单链表。
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;
}
}