1、 HashMap 原理= 桶表+链表+红黑树的结构(jdk1.8)特性
--hashMap 构造函数,有三个构造函数
1、 无参构造函数,默认初始大小16 和数据加载因子为0.75
2、一个参数数的构造函数,可以指定初始值大小,使用默认的数据加载因子0.75
3、有两个参数的构造函数,可以指定初始容量和数据加载因子0.75
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
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);
}
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity.
* @throws IllegalArgumentException if the initial capacity is negative.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
--问题一:为什么HashMap的默认值为16 容量,加载因子为0.75呢。
处于一个性能的考虑,因为每次扩容都是重新创建一个newNode;
建议: 初始化大小 = 元素个数 / 数据加载因子 +1;
加载因子: 提高空间利用率和 减少查询成本的折中,主要是泊松分布,0.75的话碰撞最小,
--问题二:设置初始化值,比如为5,那么Hashmap 是创建容量为5的容量吗?
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);
}
/**
* Returns a power of two size for the given target capacity.
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
从源码中我们可以看到,设定的初始值最终会调用tableSizeFor 函数;
这个函数返回一个给定目标2的次方的数。 所以创建的容量cp=8
--问题三: HashMap 是可以存Null 的key值,那么Null的位置hashmap会放到哪里呢?
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
从源码中可以看出,在进行put 元素操作时,会计算key的hash值,当key为null 值是放到索引值为0 的位置的。
--问题四: put操作时普通的节点是什么时候转treeNode节点?
可以看下put 的源码
/**
* 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;
if ((p = tab[i = (n - 1) & hash]) == null)
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))))
e = p;
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);
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;
}
一行行的分析
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
在进行put操作时,首先获取table对象,判断对象是否存在,不存在则重置大小。
table对象是什么?这个是hashmap内的一个对象。我们发现在构造函数中并没有初始这个table,显然这个table值为null
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
transient Node<K,V>[] table;
所以在put第一次操作时会调用resize() 方法.reSize()方法作用是
初始化或加倍表大小。如果为空,则分配与初始容量目标保持一致。
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
//to-do
}
然后继续往下走,很显然因为我们是第一次put 值,所以 tab[i=(n-1)& hash] 的对象是为null的。所以创建一个对象。
(n-1)&hash 表示查找当前元素的位置,相当于 hash %tab.length 求余数。
例如: 当n=8时,hash 值为4 ,表示tab[4%8]=tab[4] 的位置.
然后执行 newNode方法创建一个Node对象,并把key 的hash 值,key值 和value值传入,第四个参数next 对象,即相关联的对象。这样tab[i] 上就赋值成功了。
第二次put插入数据时。执行同样的操作,同时也会计算hash值,如果hash定位的索引没有值,则执行相同的操作。
++modCount;
这个modCount什么作用呢?
1、记录hashMap 内部结构被修改的次数。
2、 备用集合迭代器 fail-fast 中?
if (++size > threshold)
resize();
判断是否超过了阈值。超过则重新分配表结构。这个this.threshold = tableSizeFor(initialCapacity); 构造函数中设定的。
afterNodeInsertion(evict);
return null;
/*查找源码发现是一个空函数*/
void afterNodeInsertion(boolean evict) { }
到这里put函数执行结束了。考虑下还有这个情况。
1、 当key 的hash值相当的时候,就会走这段代码了。
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
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);
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;
}
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
p对象是一个对象,在判断的时候已经赋值了,如if ((p = tab[i = (n - 1) & hash]) == null)
上面这段代码的意思是 判断hash值是否相同,相同的化,判断key 是否相等,如果相等就e=p这一步。主要作用用于修改存在key值的value值。
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
/**这个是空函数*/
void afterNodeAccess(Node<K,V> p) { }
这段代码用于修改value。并返回旧值。这里就结束了,不在往下走了。
在看另外的情况:这里修改旧值的另一次情况。
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);
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;
}
}
我先来看else 中代码,这个是一个无限循环语句,如果里面无法跳出。就一直进行循环。
这段代码的意思是 key 的hash 值 和某上一次的key的hash值相同,所以会在查到到当前的p对象.next赋值,形成链表,这里称为 hash碰撞。会把存的值形成链表结构。
创建一个节点对象存入p.next中,指的是第一次hash碰撞,进入
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
这里有一个判断binCount 显然第一次是小于TREEIFY_THRESHOLD - 1的值的,TREEIFY_THRESHOLD=8 默认值。
假设这里是put插入值的第7次hash碰撞,每次选好 p = e; 对象赋值。
这个时候代码执行 treeifyBin(tab, hash);
这个方法做了什么呢?
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
这个方法是替换原来的链表或者把treeNode在 tab.length长度小于MIN_TREEIFY_CAPACITY=64的时候,在转化成链表结构。主要出于性能和空间使用率的考虑。
这里为了简便我们直接看else if 的代码 ?
TreeNode<K,V> p = replacementTreeNode(e, null);
这一步是转化操作,把Node对象转成一个TreeNode对象。
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
这个步骤主要是替换tab 中index=hash 这一只的对象Node 为TreeNode,如果这个TREEIFY_THRESHOLD 这个值比较大时,Node的链表就比较长,在插入或者查询时会影响性能。
TREEIFY_THRESHOLD=8 为什么呢?
这个值也必须是2 的倍数,以符合最小应为8*关于转换回普通垃圾箱的树删除.
final void treeify(Node<K,V>[] tab) {
TreeNode<K,V> root = null;
for (TreeNode<K,V> x = this, next; x != null; x = next) {
next = (TreeNode<K,V>)x.next;
x.left = x.right = null;
if (root == null) {
x.parent = null;
x.red = false;
root = x;
}
else {
K k = x.key;
int h = x.hash;
Class<?> kc = null;
for (TreeNode<K,V> p = root;;) {
int dir, ph;
K pk = p.key;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
dir = tieBreakOrder(k, pk);
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
x.parent = xp;
if (dir <= 0)
xp.left = x;
else
xp.right = x;
root = balanceInsertion(root, x);
break;
}
}
}
}
moveRootToFront(tab, root);
}
把普通node 对象转成treenode树。
为什么TreeNode 可以转化成Node对象 ?
static class Entry<K,V> extends HashMap.Node<K,V> {
Entry<K,V> before, after;
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next);
}
}
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
从代码中可以看出TreeNode 继承了Node对象,是Node对象的子类。顾可以相互转化。
上面的红黑树的查询0Logn
-----讲完了put方法,现在来说下get方式
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) {
if (first.hash == hash && // always check first node
((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;
}
get方法里面调用的是getNode方式。
在getNode方法中进行获取查询,在其中判断了请求的节点对象是否为treeNode,如果TreeNode通过getTreeNode进行获取值。
如果不是就是进行一个循环查找到has对应的位置,判断key,返回查找的对象,发现时间复杂度为O(n).
getTreeNode
--> find 方法 进行对象的查找。
public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
fail-fast 机制?
fail-fast 机制,即快速失败机制,是java集合(Collection)中的一种错误检测机制。当在迭代集合的过程中该集合在结构上发生改变的时候,就有可能会发生fail-fast,即抛出ConcurrentModificationException异常。fail-fast机制并不保证在不同步的修改下一定会抛出异常,它只是尽最大努力去抛出,所以这种机制一般仅用于检测bug。