写在前面
本文是针对JDK版本1.8的,可能与其他版本有出入。
全局变量
// 序列化id
private static final long serialVersionUID = 362498820763181265L;
// 默认容量16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// 最大容量 2的30次方
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默认负载因子 0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 当桶结点大于8时,当前链表会转换成红黑树
static final int TREEIFY_THRESHOLD = 8;
// 当桶结点小于6时,当前红黑树会转换成链表
static final int UNTREEIFY_THRESHOLD = 6;
//转红黑树时, table的最小长度
static final int MIN_TREEIFY_CAPACITY = 64;
// 存储元素的数组,transient关键字表示该属性不能被序列化
transient Node<K,V>[] table;
// 将数据转换成set的另一种存储形式,这个变量主要用于迭代功能
transient Set<Map.Entry<K,V>> entrySet;
// 元素数量
transient int size;
// 修改次数
transient int modCount;
// 阈值,当元素数量达到阈值时,会进行扩容
int threshold;
// 负载因子
final float loadFactor;
存储结构
图片来自:程序员囧辉
// 内部类 --链表结构
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; // 该结点的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; // 下一个结点
}
......
}
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
......
}
构造方法
hashmap一共有4个构造方法,如下
// 传入参数为初始容量和负载因子
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, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
重点