HashMap中的一些常量
默认的初始容量 16static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
hashmap 最大容量,当构造函数中传入的数值大于此值,将使用最大值static final int MAXIMUM_CAPACITY = 1 << 30;
hashmap的加载因子。
1,加载因子设置较大,随着数组中元素装的越多,发生的冲突的概率越大,即对应的链表越长,影响查找效率。
2.加载因子设置较小,元素很容易达到设定的阈值,发生扩容操作,数组空间还有很大部分没有利用上,造成空间浪费。因此在时间与空间上的权衡考虑DEFAULT_LOAD_FACTOR = 0.75f
树化阀值,当链表元素超过8时,hashmap存储结构由链表转化为红黑数结果,提高查找效率static final int TREEIFY_THRESHOLD = 8;
取消树阀值,在红黑树中节点数量小于6个,将其转化为链表结构UNTREEIFY_THRESHOLD = 6
最小的树化容量,链表树化红黑树条件:
1,链表中元素数量超过(>)8个;
2, 满足map中元素个数(size)大于等于64否则会先扩容,扩容对解决hash冲突更有效。static final int MIN_TREEIFY_CAPACITY = 64;
threshold表示当HashMap的size大于threshold时会执行resize操作。threshold = capacity * loadFactorthreshold
hashmap修改次数,当修改次数不匹配时,会抛出ConcurrentModificationException异常modCount
HashMap的构造函数
HashMap提供了4种构造函数。
无参构造函数
//加载因子,和初始化容量均使用默认值
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
提供初始容量和加载因子的构造函数
//使用传入的容量和加载因子初始化hashmap,并校验参数范围
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);
}
参数为map子集的构造函数
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
HashMap的节点结构
- 数组和链表节点对象为HashMap内部类 Node.
- 红黑树节点 TreeNode,继承LinkedHashMap.Entry , 而 Entry继承Node,因此 TreeNode 实际是 Node孙子.
- Node类,重写了hashCode和 equals方法,记录了当前key, value, key的hash值,以及指向后一个元素指针.
Node类
/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*/
static class Node<K,V> implements Map.Entry<K,V> {
//记录当前节点的hash值
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 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;
}
}
HashMap的put实现
put方法:
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);
}
put方法的核心实现:putVal()方法
/**
* 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;
//初始化数组
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//确定元素在数组中的位置。
//hashmap通过 数组长度 n - 1 与上key的hash值,来确定元素的位置,那么是怎么保证永远结果在数组长度范围内呢?
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//比较第一个元素(数组中的结点)的hash值相等,key相等`
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//将第一个元素赋值给e,用e来记录`
e = p;
//hash值不相等,即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) {
//尾插,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;
}
}
// existing mapping for key,key值已经存在,新的value替换旧的value,并返回旧值
if (e != null) {
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//修改次数增加
++modCount;
if (++size > threshold)
//到达阀值,hashmap重新进行resize()
resize();
afterNodeInsertion(evict);
return null;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。