HashMap的数据结构:
数组+链表,数组中元素是个链表,存储Key的hashcode碰撞的元素
其中元素的节点为:
static class Node<K,V> implements Map.Entry<K,V> { 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; } }
每个Node含有指向下一个Node的指针
数组(HashMap大小)的初始长度16
/** * The default initial capacity - MUST be a power of two. */ static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
数组的增长因子,0.75
/** * The load factor used when none specified in constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f;
HashMap的实现重点需要注意的在两个方面,一个是链表结构,一个是table的resize()
HashMap处理hashcode碰撞的方式用链表,hashcode相同的元素头尾相连组成一个单链,并把最开始的那个节点存储在数组中,访问的时候,先通过hash(key)找到数组下标,再迭代单链找到equals()的value,然后返回
resize的时候,如果当前数组的占用率达到负载因子0.75,则会触发一次resize(),增长量为原来容量(table.length)的一倍,newCap = oldCap << 1
然后把老数组的数据迁移到新数组
//=============================================================分割线====================================================================
HashMap和HashTable的区别:
他们的结构差不多,只不过HashTable是线程安全的,HashTable是所有暴露的操作都加锁,synchronized,这种情况下性能比较低,容易引起活跃性问题
HashTable跟java.util.Collections#synchronizedMap很接近
HashMap允许key和value为null
HashTable不允许key和value为null
ConcurrentHashMap也是线程安全的,是采用CAS的方式来处理并发操作,如果单链比较长就坍缩为一个红黑树,logn的时间复杂度
ConcurrentHashMap要分jdk1.8之前还是之后
1.8之前的ConcurrentHashMap是采用分段(Segment)的方式,加锁时直接在Segment上加锁,缩小了加锁范围,提高了性能
1.8之后的ConcurrentHashMap是重写的,加锁范围进一步缩小,采用CAS将加锁范围缩小到单个数组元素
性能上ConcurrentHashMap比前面的要高