数组+链表:存在性能最坏情况O(n)
Java8以前,HashMap底层数据结构采用数组+链表的结构。
数组特点:查询快,增删慢。
链表特点:查询慢,增删较快。
HashMap:结合了数组和链表的优势。同时HashMap的操作是非Synchronized,因此效率比较高。
Java7的HashMap的put方法思路
put源码:
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
addEntry源码:
/**
* Adds a new entry with the specified key, value and hash code to
* the specified bucket. It is the responsibility of this
* method to resize the table if appropriate.
*
* Subclass overrides this to alter the behavior of put method.
*/
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
方法简述:
1、初始化HashMap,若Entry数组类型的table为空,inflated(膨胀,扩容意思)一个table,threshold默认=初始容量=16;
2、对key求Hash值,然后再计算table下标;
3、如果没有碰撞,即数组中没有相应的键值对,直接放入桶(bucket)中,如果碰撞了,以链表的方式链接到后面;
4、如果键值对已经存在就替换旧值;
5、如果桶满了(容量16*加载因子0.75),就需要扩容resize();
但是,存在坏情况:如果通过哈希散列运算得到的是同一个值,即总是分配到同一个桶中,使某个桶的链表长度很长。
由于链表查询需要从头开始遍历,最坏情况下,HashMap性能变为O(n)。
数组+链表+红黑树:性能提高到O(logn)
Java8以后,HashMap底层数据结构采用数组+链表+红黑树的结构。
通过常量TREEIFY_THRESHOLD=8和UNTREEIFY_THRESHOLD=6来控制链表与红黑树的转化。
Java8的HashMap的putVal方法思路
putVal源码:
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;
}
在Java7源码基础上增加了链表和红黑树的转化。
如果链表长度超过阈值8,就把链表转换成红黑树,如果链表长度低于6,就把红黑树转回链表。改变了最坏情况下O(n),性能提高到O(logn)。
注意:Java7中数组里的元素叫Entry,Java8及以后改名为Node(节点)。