首先要记住核心, HashMap的底层是数组+单向链表, 超过THRESHOLD设定的值 对应的数组下标下的链表会转换成红黑树(但是将链表转换成红黑树前会判断,如果当前数组的长度小于 64,那么会选择先进行数组扩容,而不是转换为红黑树)
没有深入了解红黑树 但是不影响看代码 有关tree的就是涉及到红黑树的
删了很多的简单的代码. 总体看下来官方代码就是清晰,认真看完一个其他发现其实也差不多
一定要根据数据结构去看
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
private static final long serialVersionUID = 362498820763181265L;
//初始容量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// 最大值 超过20亿
static final int MAXIMUM_CAPACITY = 1 << 30;
// 超过容量* LOAD_FACTOR 就会扩容 (16 和 0.75 肯定是经过大量计算得出的)
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//单个链表长超过就会转换成红黑树
static final int TREEIFY_THRESHOLD = 8;
//从树转换回来
static final int UNTREEIFY_THRESHOLD = 6;
//hashMap中元素数量大于64时,也会转为红黑树结构。
static final int MIN_TREEIFY_CAPACITY = 64;
//就是链表中的每个节点
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V 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 int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
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 hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//返回最接近的2的幂次方
static final int tableSizeFor(int cap) {
}
//就是存储节点和链表的数组(数据存放的地方)
transient Node<K,V>[] table;
//用于转换进行迭代
transient Set<Map.Entry<K,V>> entrySet;
//元素的数量
transient int size;
//结构改变的次数
transient int modCount;
// 决定何时绝定扩容
int threshold;
final float loadFactor;
//四种构造方法
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; // all other fields defaulted
}
public HashMap(Map<? extends K,