HashMap的初步介绍:
HashMap里存放的是键值对,其中key值可以为null,但不能重重复,HashMap继承于AbstractMap类,实现了Map、Cloneable、java.io.Serializable接口,HashMap的实现不是同步的,这意味着它不是线程安全的。
HashMap类有一个叫做Entry的内部类,底层实现主要是一个名叫table的默认大小为16的数组。在这个Entry的内部类里包含了key-value作为实例变量。
当HashMap里存放key-value对的时候,会实例化一个Entry对象,该对象存储在table中。
HashMap扩容:
HashMap的构造函数中有一个参数,叫做装载因子,它表示的是容量扩充之前,要达到多满的一种尺度(默认为0.75),扩容时,table的数组大小会变为原来的两倍。
HashMap的冲突:
当我们放入一个键值对的时候,会调用key的hashcode()函数,来计算出hash值来映射到对应的数组下标,当不同的key值,出现相同的hash值,即有两个不同的Entry对象放到了同一个地址上,这是就是发生了冲突。
冲突解决:当有两个key有相同的hash值,他们以链表的形式存储
HashMap的put和get方法:
让我们看下put方法的实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
/**
* Associates the specified value with the specified key in this map. If the
* map previously contained a mapping for the key, the old value is
* replaced.
*
* @param key
* key with which the specified value is to be associated
* @param value
* value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or <tt>null</tt>
* if there was no mapping for <tt>key</tt>. (A <tt>null</tt> return
* can also indicate that the map previously associated
* <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
if (key == null )
return putForNullKey(value);
int hash = hash(key.hashCode());
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 ;
}
|
现在我们一步一步来看下上面的代码。
对key做null检查。如果key是null,会被存储到table[0],因为null的hash值总是0。
key的hashcode()方法会被调用,然后计算hash值。hash值用来找到存储Entry对象的数组的索引。有时候hash函数可能写的很不好,所以JDK的设计者添加了另一个叫做hash()的方法,它接收刚才计算的hash值作为参数。如果你想了解更多关于hash()函数的东西,可以参考:hashmap中的hash和indexFor方法
indexFor(hash,table.length)用来计算在table数组中存储Entry对象的精确的索引。
在我们的例子中已经看到,如果两个key有相同的hash值(也叫冲突),他们会以链表的形式来存储。所以,这里我们就迭代链表。
- 如果在刚才计算出来的索引位置没有元素,直接把Entry对象放在那个索引上。
- 如果索引上有元素,然后会进行迭代,一直到Entry->next是null。当前的Entry对象变成链表的下一个节点。
- 如果我们再次放入同样的key会怎样呢?逻辑上,它应该替换老的value。事实上,它确实是这么做的。在迭代的过程中,会调用equals()方法来检查key的相等性(key.equals(k)),如果这个方法返回true,它就会用当前Entry的value来替换之前的value。
Get:
现在我们来看下get方法的实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
/**
* Returns the value to which the specified key is mapped, or {@code null}
* if this map contains no mapping for the key.
*
* <p>
* More formally, if this map contains a mapping from a key {@code k} to a
* value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise it returns
* {@code null}. (There can be at most one such mapping.)
*
* </p><p>
* A return value of {@code null} does not <i>necessarily</i> indicate that
* the map contains no mapping for the key; it's also possible that the map
* explicitly maps the key to {@code null}. The {@link #containsKey
* containsKey} operation may be used to distinguish these two cases.
*
* @see #put(Object, Object)
*/
public V get(Object key) {
if (key == null )
return getForNullKey();
int hash = hash(key.hashCode());
for (Entry<k , V> e = table[indexFor(hash, table.length)]; e != null ; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
return null ;
}
|
当你理解了hashmap的put的工作原理,理解get的工作原理就非常简单了。当你传递一个key从hashmap总获取value的时候:
对key进行null检查。如果key是null,table[0]这个位置的元素将被返回。
key的hashcode()方法被调用,然后计算hash值。
indexFor(hash,table.length)用来计算要获取的Entry对象在table数组中的精确的位置,使用刚才计算的hash值。
在获取了table数组的索引之后,会迭代链表,调用equals()方法检查key的相等性,如果equals()方法返回true,get方法返回Entry对象的value,否则,返回null。
要牢记以下关键点:
- HashMap有一个叫做Entry的内部类,它用来存储key-value对。
- 上面的Entry对象是存储在一个叫做table的Entry数组中。
- table的索引在逻辑上叫做“桶”(bucket),它存储了链表的第一个元素。
- key的hashcode()方法用来找到Entry对象所在的桶。
- 如果两个key有相同的hash值,他们会被放在table数组的同一个桶里面。
- key的equals()方法用来确保key的唯一性。
- value对象的equals()和hashcode()方法根本一点用也没有。
最后,补充几个拓展的问题:
1. 当重新调整HashMap大小时会存在什么问题?(在面试中被面试官问到)
当重新调整HashMap大小的时候,在多线程的情况下,可能存在条件竞争,因为如果两个线程都发现HashMap需要重新调整大小了,它们会同时试着调整大小。在调整大小的过程中,存储在链表中的元素的次序会反过来,因为移动到新的bucket位置的时候,HashMap并不会将元素放在链表的尾部,而是放在头部,这是为了避免尾部遍历(tail traversing)。如果条件竞争发生了,那么就死循环了。
2. HashMap中的key可以是任何对象或数据类型吗?
可以为null,但不能是可变对象,如果是可变对象的话,对象中的属性改变,则对象的HashCode也进行相应的改变,导致下次无法查找到已存在Map中的数据。
如果可变对象在HashMap中被用作键,那就应该在改变对象状态的时候,不要改变它的哈希值,我们只需要保证成员变量的改变能保证该对象的哈希值不变即可。
一般情况下,对象的equals方法相等,hashcode方法也应该相等(不然两个相等key值的Entry对象存放在了不同的地址中,这和HashMap的定义是冲突的)
同样的,hashcode方法不等的话,equals方法也应该不等,但是hashcode方法相等的话,equals方法可以相等,可以不等。
其中部分内容借鉴:http://www.importnew.com/10620.html