//-----------------------------------------------------------------------------------
转出处:http://blog.csdn.net/chdjj
作者:RowandJJ
//-----------------------------------------------------------------------------------
注:以下源码基于jdk1.7.0_11
之前的几篇文章介绍了List集合中一些比较常见的类,比如ArrayList、LinkedList、Vector等。本篇文章将介绍集合框架的另一块内容——Map集合。本文主要介绍HashMap。
先回顾下哈希表。
哈希表定义:根据设定的hash函数和处理冲突的方式(开放定址、公共溢出区、链地址、重哈希...)将一组关键字映射到一个有限的连续的地址集上(即bucket数组或桶数组),并以关键字在地址集中的“像”作为记录在表中的存储位置,这种表称为hash表,这一映射过程称为散列,所得存储位置称为哈希地址或散列地址。hash表具有良好的查找性能,在冲突概率很小的情况下,时间复杂度为O(1)。
装载因子:loadfactor = 表中填入的记录数/哈希表的长度.所以loadfactor标志着哈希表的装满程度。
直观的看,装载因子越小,发生冲突的概率越小(因为桶中还没装几个数据,就需要扩容),也就是查找性能越好,但同时浪费的空间就变大。相反,装载因子越大,发生冲突的概率越大(等到桶快填满时才能扩容,比如,采用链表法处理冲突,在此种情况下,会导致链表过长),查找性能越差,同时浪费的空间会减少。
后面我们会看到,HashMap默认的装载因子为0.75.
下面,依然是自顶向下分析,首先看Map接口:
- public interface Map<K,V> {
-
- int size();
- boolean isEmpty();
- boolean containsKey(Object key);
- boolean containsValue(Object value);
- V get(Object key);
-
- V put(K key, V value);
- V remove(Object key);
-
- void putAll(Map<? extends K, ? extends V> m);
- void clear();
-
-
- Set<K> keySet();
- Collection<V> values();
- Set<Map.Entry<K, V>> entrySet();
-
- interface Entry<K,V> {
- K getKey();
- V getValue();
- V setValue(V value);
- boolean equals(Object o);
- int hashCode();
- }
-
-
- boolean equals(Object o);
- int hashCode();
- }
Map接口定义了Map集合的操作规范,具体实现交由实现类完成,其内部有个接口Entry,代表一个键值对.
AbstractMap是一个抽象类,其实现了Map接口中的大部分函数。
- public abstract class AbstractMap<K,V> implements Map<K,V>
下面来看几个方法:
- public boolean containsKey(Object key) {
- Iterator<Map.Entry<K,V>> i = entrySet().iterator();
- if (key==null) {
- while (i.hasNext()) {
- Entry<K,V> e = i.next();
- if (e.getKey()==null)
- return true;
- }
- } else {
- while (i.hasNext()) {
- Entry<K,V> e = i.next();
- if (key.equals(e.getKey()))
- return true;
- }
- }
- return false;
- }
- public boolean containsValue(Object value) {
- Iterator<Entry<K,V>> i = entrySet().iterator();
- if (value==null) {
- while (i.hasNext()) {
- Entry<K,V> e = i.next();
- if (e.getValue()==null)
- return true;
- }
- } else {
- while (i.hasNext()) {
- Entry<K,V> e = i.next();
- if (value.equals(e.getValue()))
- return true;
- }
- }
- return false;
- }
首先是containsKey和containsValue方法,需要注意的是这里的key和value是允许为空的,也就是说其子类默认是支持null键和值的。这里的entrySet方法是个抽象方法:- public abstract Set<Entry<K,V>> entrySet();
abstractMap并没有实现put方法,而简单的抛出了异常,这要求子类必须复写此方法:
- public V put(K key, V value) {
- throw new UnsupportedOperationException();
- }
但是其却实现了get方法:- public V get(Object key) {
- Iterator<Entry<K,V>> i = entrySet().iterator();
- if (key==null) {
- while (i.hasNext()) {
- Entry<K,V> e = i.next();
- if (e.getKey()==null)
- return e.getValue();
- }
- } else {
- while (i.hasNext()) {
- Entry<K,V> e = i.next();
- if (key.equals(e.getKey()))
- return e.getValue();
- }
- }
- return null;
- }
下面来看HashMap。- public class HashMap<K,V>
- extends AbstractMap<K,V>
- implements Map<K,V>, Cloneable, Serializable
HashMap继承了AbstractMap类,并实现了Map接口以及Cloneable、Serializable接口。
其成员变量如下:
- static final int DEFAULT_INITIAL_CAPACITY = 16;
- static final int MAXIMUM_CAPACITY = 1 << 30;
- static final float DEFAULT_LOAD_FACTOR = 0.75f;
- transient Entry<K,V>[] table;
- transient int size;
- int threshold;
- final float loadFactor;
- transient int modCount;
- static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;
这里我们得到如下信息:1.HashMap的默认大小为16,即桶数组的默认长度为16;2.HashMap的默认装载因子是0.75;3.HashMap内部的桶数组存储的是Entry对象,也就是键值对对象。
再看构造器:
- 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);
-
-
- int capacity = 1;
- while (capacity < initialCapacity)
- capacity <<= 1;
- this.loadFactor = loadFactor;
- threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
-
- table = new Entry[capacity];
- useAltHashing = sun.misc.VM.isBooted() &&
- (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
- init();
- }
-
- public HashMap(int initialCapacity) {
- this(initialCapacity, DEFAULT_LOAD_FACTOR);
- }
- public HashMap() {
- this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
- }
- public HashMap(Map<? extends K, ? extends V> m) {
- this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
- DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
- putAllForCreate(m);
- }
-
-
- void init() {
- }
需要注意的点:
1.构造器支持指定初始容量和装载因子,为避免数组扩容带来的性能问题,建议根据需求指定初始容量。装载因子尽量不要修改,0.75是个比较靠谱的值。
2.实际的容量capacity一般情况下是大于我们传进去的initialCapacity的,因为内部会通过一个循环去找到一个比initialCapacity大且为2的整数次幂的一个数作为实际容量。除非传进去的数恰好为2的整数次方(capacity取2的整数次幂,是为了使不同hash值发生碰撞的概率较小,这样就能使元素在哈希表中均匀地散列。)。
通过前面的分析,我们知道了HashMap内部通过Entry数组保存键值对,那么这个Entry是怎么实现的呢?
接下来我们看下Entry的实现:
- static class Entry<K,V> implements Map.Entry<K,V> {
- final K key;
- V value;
- Entry<K,V> next;
- int hash;
-
-
-
-
- Entry(int h, K k, V v, Entry<K,V> n) {
- value = v;
- next = n;
- key = k;
- hash = h;
- }
- public final K getKey() {
- return key;
- }
- public final V getValue() {
- return value;
- }
-
- public final V setValue(V newValue) {
- V oldValue = value;
- value = newValue;
- return oldValue;
- }
- public final boolean equals(Object o) {
- if (!(o instanceof Map.Entry))
- return false;
- Map.Entry e = (Map.Entry)o;
-
- Object k1 = getKey();
- Object k2 = e.getKey();
- if (k1 == k2 || (k1 != null && k1.equals(k2))) {
- Object v1 = getValue();
- Object v2 = e.getValue();
- if (v1 == v2 || (v1 != null && v1.equals(v2)))
- return true;
- }
- return false;
- }
- public final int hashCode() {
- return (key==null ? 0 : key.hashCode()) ^
- (value==null ? 0 : value.hashCode());
- }
- public final String toString() {
- return getKey() + "=" + getValue();
- }
-
-
-
-
-
- void recordAccess(HashMap<K,V> m) {
- }
-
-
-
-
- void recordRemoval(HashMap<K,V> m) {
- }
- }
需要注意的点:
1.HashMap内部数组存储的是键值对,也就是Entry对象;
2.Entry对象保存了键、值,并持有一个next指针指向下一个Entry对象(HashMap通过链表法解决冲突);
3.Entry可以通过setValue设置值,但不允许设置键.
下面我们研究下HashMap中比较重要的方法。从put开始:
- public V put(K key, V value) {
- 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;
- }
put方法是向hashMap中添加一个键值对,这个方法需要注意的有:
1.允许键为null。put方法会针对null键做相应的处理,调用pullforNullKey方法:
- private V putForNullKey(V value) {
-
-
- for (Entry<K,V> e = table[0]; e != null; e = e.next) {
- if (e.key == null) {
- V oldValue = e.value;
- e.value = value;
- e.recordAccess(this);
- return oldValue;
- }
- }
-
- modCount++;
- addEntry(0, null, value, 0);
- return null;
- }
2.不允许两个键相同,如果键相同,那么后插入的键所对应的值会覆盖之前的值。
3.HashMap是通过调用hash()方法获得键的hash值,并通过indexFor方法找到实际插入位置,具体代码如下:
- final int hash(Object k) {
- int h = 0;
- if (useAltHashing) {
- if (k instanceof String) {
- return sun.misc.Hashing.stringHash32((String) k);
- }
- h = hashSeed;
- }
- h ^= k.hashCode();
- h ^= (h >>> 20) ^ (h >>> 12);
- return h ^ (h >>> 7) ^ (h >>> 4);
- }
-
- static int indexFor(int h, int length) {
- return h & (length-1);
- }
4.put方法通过addEntry方法将键值插到合适位置:
5.当容量超过阈值(threshold)时,会发生扩容,扩容后的数组是原数组的两倍。
- 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);
- }
- void createEntry(int hash, K key, V value, int bucketIndex) {
- Entry<K,V> e = table[bucketIndex];
- table[bucketIndex] = new Entry<>(hash, key, value, e);
- size++;
- }
这个resize方法就是扩容方法:- 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];
- boolean oldAltHashing = useAltHashing;
- useAltHashing |= sun.misc.VM.isBooted() &&
- (newCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
- boolean rehash = oldAltHashing ^ useAltHashing;
- transfer(newTable, rehash);
- table = newTable;
- threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
- }
- void transfer(Entry[] newTable, boolean rehash) {
- int newCapacity = newTable.length;
- for (Entry<K,V> e : table) {
- while(null != e) {
- Entry<K,V> next = e.next;
- if (rehash) {
- e.hash = null == e.key ? 0 : hash(e.key);
- }
- int i = indexFor(e.hash, newCapacity);
- e.next = newTable[i];
- newTable[i] = e;
- e = next;
- }
- }
- }
6.扩容操作需要开辟新数组,并对原数组中所有键值对重新散列,非常耗时。我们应该尽量避免HashMap扩容。
再来看get方法:
- public V get(Object key) {
- if (key == null)
- return getForNullKey();
- Entry<K,V> entry = getEntry(key);
-
- return null == entry ? null : entry.getValue();
- }
这个getForNullKey方法就是在数组0索引位上的链表去寻找null键:- private V getForNullKey() {
- for (Entry<K,V> e = table[0]; e != null; e = e.next) {
- if (e.key == null)
- return e.value;
- }
- return null;
- }
而这个getEntry方法就是通过键生成hash值,然后得到其在数组的索引位,查找该位置的链表,找到第一个满足的键,并返会Entry对象:
- final Entry<K,V> getEntry(Object key) {
- int hash = (key == null) ? 0 : hash(key);
- 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 != null && key.equals(k))))
- return e;
- }
- return null;
- }
再看下remove方法:- public V remove(Object key) {
- Entry<K,V> e = removeEntryForKey(key);
- return (e == null ? null : e.value);
- }
- final Entry<K,V> removeEntryForKey(Object key) {
- int hash = (key == null) ? 0 : hash(key);
- int i = indexFor(hash, table.length);
- Entry<K,V> prev = table[i];
- Entry<K,V> e = prev;
- while (e != null) {
- Entry<K,V> next = e.next;
- Object k;
- if (e.hash == hash &&
- ((k = e.key) == key || (key != null && key.equals(k)))) {
- modCount++;
- size--;
- if (prev == e)
- table[i] = next;
- else
- prev.next = next;
- e.recordRemoval(this);
- return e;
- }
- prev = e;
- e = next;
- }
- return e;
- }
最后看下clear方法:- public void clear() {
- modCount++;
- Entry[] tab = table;
- for (int i = 0; i < tab.length; i++)
- tab[i] = null;
- size = 0;
- }
总结:
1.HashMap的默认大小为16,即桶数组的默认长度为16;
2.HashMap的默认装载因子是0.75;
3.HashMap内部的桶数组存储的是Entry对象,也就是键值对对象。
4.构造器支持指定初始容量和装载因子,为避免数组扩容带来的性能问题,建议根据需求指定初始容量。装载因子尽量不要修改,0.75是个比较靠谱的值。
5.桶数组的长度始终是2的整数次方(大于等于指定的初始容量),这样做可以减少冲突概率,提高查找效率。(可以从indexfor函数中看出,h&(length-1),若length为奇数,length-1为偶数那么h&(length-1)结果的最后一位必然为0,也就是说所有键都被散列到数组的偶数下标位置,这样会浪费近一半空间。另外,length为2的整数次方也保证了h&(length-1)与h%length等效).
6.HashMap接受null键;
7.HashMap不允许键重复,但是值是可以重复的。若键重复,那么新值会覆盖旧值。
8.HashMap通过链表法解决冲突问题,每个Entry都有一个next指针指向下一个Entry,冲突元素(不是键相同,而是hash值相同)会构成一个链表。并且最新插入的键值对始终位于链表首部。
9.当容量超过阈值(threshold)时,会发生扩容,扩容后的数组是原数组的两倍。扩容操作需要开辟新数组,并对原数组中所有键值对重新散列,非常耗时。我们应该尽量避免HashMap扩容。
10.HashMap非线程安全。
0 0