HashMap底层实现JDK1.7&JDK1.8
Map结构
-
Map中的key是无序的、不能重复的,使用set可以存储所有的key; key所在的类要重写equals()和hashcode()方法
-
Map中的value是无序的、可以重复的,使用Collection可以存储所有的value; value所在的类要重写equals
-
key和value组成了entry对象,该对象是无序的、不可重复的,可以使用set来存储
HashMap的底层实现原理
- HashMap创建的流程示意图(以jdk1.7为例)
- 扩容问题
在添加数据的过程中,随着数据量的不断增加,就会涉及到扩容问题,默认的扩容方式:扩容为原来容量的两倍,并将原有的数据复制过来.
HashMap在JDK1.7中的实现
//调用hashmap的有参构造
public HashMap(int initialCapacity, float loadFactor) { //初始化长度initialCapacity:16;加载因子loadFactor:0.75
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;
threshold = initialCapacity;//临界值
init();
}
new HashMap()其实就做了上面的这些操作,在底层创建了一个长度为16的Entry[] table一维数组;
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null) //hashmap中可以存放null值的key,而Hashtable就不存在
return putForNullKey(value);
int hash = hash(key); //获取当前key的hash值
int i = indexFor(hash, table.length);//经过运算,得到在数组中的存放位置
for (Entry<K,V> e = table[i]; e != null; e = e.next) { //这里是在遍历该位置上的元素,该位置上可能是一个元素也有可能是链表,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;
}
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {//当数组的长度大于临界值12,并且该位置不为空的时候,就需要扩容了;如果该位置为null,那么直接将元素放到该位置即可
resize(2 * table.length);//容量扩大为原来的两倍
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
//扩容
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
Entry[] newTable = new Entry[newCapacity];
transfer(newTable, initHashSeedAsNeeded(newCapacity));
table = newTable;
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];//先将该位置伤感的数据取出来,放到e中
table[bucketIndex] = new Entry<>(hash, key, value, e);//然后新建一个Entry对象,把e作为参数,其实就是指的next,作为下一个对象,把下载的key-value键值对对象放在该数组的位置上,具体可以看下面的Entry对象的源码
size++;
}
//Entry对象
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
HashMap在JDK1.8中的实现
- jdk1.8中的源码
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;
}
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
- 源码说明
1. 第一次put value得时候,调用resize()方法; resize()方法中会创建一个长度为16的Node<K,V>[] newTab数组;
2. 如果不是第一次添加元素,那就要通过与运算得到该元素在数组中存放的位置,判断该位置上是否有值,如果没有值,那么不需要做其他操作,执行放值就可以了;
3. 如果该位置上有值,那么就要比较该位置上的元素和它的链表上所有的值的哈希值,如果哈希相同,再继续调用equals()方法判断;如下图所示
HashMap1.7与1.8中底层实现的不同
- jdk1.8中new HashMap();底层没有创建长度为16的数组
- jdk1.8中底层的数组是Node[]而不是Entry[];
- 首次调用put()方法时,底层创建长度为16的数组,提高了效率
- jdk7中底层结构中(Entry[]数组中):数组+链表; jdk8中底层结构(Node[]数组):数组+链表+红黑树
jdk8中什么时候要使用红黑树:当数组中某一个索引位置上的元素以链表的方式存在的元素的个数>8 并且数组的长度>64时,此时数组上所有的元素都会采用红黑树的方式存储;
有关HashMap的面试题
- 谈谈你对HashMap中put/get方法的认识
- HashMap的扩容机制
- 默认大小: DEFAULT_INITIAL_CAPACITY:16
- 什么是负载因子(或填充比): DEFAULT_LOAD_FACTOR:0.75
- 什么是吞吐临界值(或阈值、threshold): 默认大小*填充因子=12
- hashmap线程安全吗,多线程往hashmap里加数据会怎么样?
答:HasnMap是线程不安全的,可以看一下这篇博客解析为什么hashmap是线程不安全的
LinkedHashMap的源码解读
- 这里补充一下LinkedHashMap的源码解读,LinkedHashMap可以有顺序的读取写入LinkedHashMap中的数值,有顺序的输出;
eg:
@Test
public void test2() {
LinkedHashMap map = new LinkedHashMap();
map.put("张三",23);
map.put("李四",24);
map.put("王五",25);
System.out.println(map);
//输出:{张三=23, 李四=24, 王五=25}
}
- 解读:LinkedHashMap中没有put方法,但是它继承了HashMap接口,所以调用的的是HashMap的put方法;但是在创建一个新的对象时候,LinkedHashMap重写了NewNode()方法
Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
LinkedHashMap.Entry<K,V> p =
new LinkedHashMap.Entry<K,V>(hash, key, value, e);
linkNodeLast(p);
return p;
}
//该Entry继承了HashMap中的Node,所以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);
}
}
HashMap的遍历
@Test
public void test3() {
HashMap map = new HashMap();
map.put("张三",23);
map.put("李四",24);
map.put("王五",25);
//遍历所有的key,key的存储是用Set来存的,key不可以重复
Set set = map.keySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
//遍历苏所有的value,value的值是可以重复的,所以只能用Collection来存储
Collection values = map.values();
for (Object obj: values) {
System.out.println(obj);
}
}
@Test
public void test4() {
HashMap map = new HashMap();
map.put("张三",23);
map.put("李四",24);
map.put("王五",25);
//(1)遍历所有的键值对对象Entry(k,v)
Set set1 = map.entrySet();
Iterator iterator1 = set1.iterator();
while (iterator1.hasNext()) {
Object obj = iterator1.next();
//entrySe集合中所有的元素都是entry对象
Map.Entry entry = (Map.Entry) obj;
System.out.println(entry.getKey()+ "--------" + entry.getValue());
}
//(2)遍历所有的键值对对象Entry(k,v)
Set set2 = map.keySet();
Iterator iterator2 = set2.iterator();
while (iterator2.hasNext()) {
Object key = iterator2.next();//获取key的值
Object value = map.get(key);//根据key的值获取value的值
System.out.println(key + "-----------" + value);
}
}