几个重要的变量:
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;//初始大小
static final int MAXIMUM_CAPACITY = 1 << 30;//map中最多可以容纳的数量
static final float DEFAULT_LOAD_FACTOR = 0.75f; //与当前容量大小决定扩容极限值,如默认的容量(16),默认的扩容极限值(16 * 0.75 = 12);如果size达到12时,进行下次扩容,容量和极限值均扩容成原来的两倍,32,24;
构造方法
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);
}
put(K key, V value)
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//对key进行hash
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
transient Node<K,V>[] table; //Node是单向链表的节点,When allocated, length is always a power of two.
// @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; //resize(): Initializes or doubles table size.此处时初始化
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null); //如果目标index目前的元素是空的则直接赋值就行
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p; //key已存在map中,更新值
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); //以链表的形式将同一index的数据组织起来
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;
}
final Node<K, V>[] resize() {
...
//初始大小为static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//计算得出新数组的大小,成倍增长 newThr = oldThr << 1
//如果达到MAXIMUM_CAPACITY,其他不变,threshold = Integer.MAX_VALUE,return原数组
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab; //更新成员变量的值
...
//将旧数组的数据按序迁移至新数组
}
put方法中含有的信息较多,可以看到HashMap内部是数组+链表的形式来存储数据的,每个数据被组装成链表的节点。
get(Object key)
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;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) { //取到数组中对应index的链表的首节点
if (first.hash == hash && // 从首节点开始遍历取出目标元素
((k = first.key) == key || (key != null && key.equals(k))))
return first;
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;
}
如果判断元素是否是目标元素:node.hash == hash && node.key == key || (key != null && key.equals(k))
remove(Object key)
public boolean remove(Object key, Object value) {
return removeNode(hash(key), key, value, true, true) != null;
}
//return the node, or null if none
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) { //通过hash快速找到对应的index
Node<K,V> node = null, e; K k; V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
} //遍历index中的链表元素,找到目标节点
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}//将目标节点从链表中移除
}
return null;
}
replace(K key, V value)
public V replace(K key, V value) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) != null) {
V oldValue = e.value;
e.value = value;
afterNodeAccess(e);
return oldValue;
}
return null;
}
//well,主要分析下面这个方法
public boolean replace(K key, V oldValue, V newValue) {
Node<K,V> e; V v;
//getNode()在get()方法中分析过了
if ((e = getNode(hash(key), key)) != null &&
((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
e.value = newValue; //替换目标节点的值
afterNodeAccess(e);
return true;
}
return false;
}
clear()
public void clear() {
Node<K,V>[] tab;
modCount++;
if ((tab = table) != null && size > 0) {
size = 0;
for (int i = 0; i < tab.length; ++i)
tab[i] = null; //清空数组即可
}
}
Q:为什么扩容因子是0.75?