深入JDK源代码之HashMap实现

来源:互联网 发布:java项目立项流程 编辑:程序博客网 时间:2024/05/11 21:58

http://zengzhaoshuai.iteye.com/blog/1131890

以下是JDK1.6中文版的对HashMap的具体介绍:  

    基于哈希表的 Map 接口的实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。(除了非同步和允许使用 null 之外,HashMap 类与 Hashtable 大致相同。)此类不保证映射的顺序,特别是它不保证该顺序恒久不变。 
    此实现假定哈希函数将元素适当地分布在各桶之间,可为基本操作(get 和 put)提供稳定的性能。迭代 collection 视图所需的时间与 HashMap 实例的“容量”(桶的数量)及其大小(键-值映射关系数)成比例。所以,如果迭代性能很重要,则不要将初始容量设置得太高(或将加载因子设置得太低)。 
    HashMap 的实例有两个参数影响其性能:初始容量 和加载因子。容量 是哈希表中桶的数量,初始容量只是哈希表在创建时的容量。加载因子 是哈希表在其容量自动增加之前可以达到多满的一种尺度。当哈希表中的条目数超出了加载因子与当前容量的乘积时,则要对该哈希表进行 rehash 操作(即重建内部数据结构),从而哈希表将具有大约两倍的桶数。 
    通常,默认加载因子 (0.75) 在时间和空间成本上寻求一种折衷。加载因子过高虽然减少了空间开销,但同时也增加了查询成本(在大多数 HashMap 类的操作中,包括 get 和 put 操作,都反映了这一点)。在设置初始容量时应该考虑到映射中所需的条目数及其加载因子,以便最大限度地减少 rehash 操作次数。如果初始容量大于最大条目数除以加载因子,则不会发生 rehash 操作。 
    如果很多映射关系要存储在 HashMap 实例中,则相对于按需执行自动的 rehash 操作以增大表的容量来说,使用足够大的初始容量创建它将使得映射关系能更有效地存储。 

下面是HashMap中的方法: 
Java代码  收藏代码
  1. void clear()   
  2.           从此映射中移除所有映射关系。   
  3.  Object clone()   
  4.           返回此 HashMap 实例的浅表副本:并不复制键和值本身。   
  5.  boolean containsKey(Object key)   
  6.           如果此映射包含对于指定键的映射关系,则返回 true。   
  7.  boolean containsValue(Object value)   
  8.           如果此映射将一个或多个键映射到指定值,则返回 true。   
  9.  Set<Map.Entry<K,V>> entrySet()   
  10.           返回此映射所包含的映射关系的 Set 视图。   
  11.  V get(Object key)   
  12.           返回指定键所映射的值;如果对于该键来说,此映射不包含任何映射关系,则返回 null。   
  13.  boolean isEmpty()   
  14.           如果此映射不包含键-值映射关系,则返回 true。   
  15.  Set<K> keySet()   
  16.           返回此映射中所包含的键的 Set 视图。   
  17.  V put(K key, V value)   
  18.           在此映射中关联指定值与指定键。   
  19.  void putAll(Map<? extends K,? extends V> m)   
  20.           将指定映射的所有映射关系复制到此映射中,这些映射关系将替换此映射目前针对指定映射中所有键的所有映射关系。   
  21.  V remove(Object key)   
  22.           从此映射中移除指定键的映射关系(如果存在)。   
  23.  int size()   
  24.           返回此映射中的键-值映射关系数。   
  25.  Collection<V> values()   
  26.           返回此映射所包含的值的 Collection 视图。   

下面深入HashMap源代码,详解它的具体实现: 

一、HashMap的数据结构: HashMap用了一个名字为table的Entry类型数组;数组中的每一项又是一个Entry链表。 
 

Java代码  收藏代码
  1. // 默认的初始化大小  
  2. static final int DEFAULT_INITIAL_CAPACITY = 16;  
  3. // 最大的容量  
  4. static final int MAXIMUM_CAPACITY = 1 << 30;  
  5. // 负载因子  
  6. static final float DEFAULT_LOAD_FACTOR = 0.75f;  
  7. // 储存key-value键值对的数组,一个键值对对象映射一个Entry对象  
  8. transient Entry[] table;  
  9. // 键值对的数目  
  10. transient int size;  
  11. // 调整HashMap大小门槛,该变量包含了HashMap能容纳的key-value对的极限,它的值等于HashMap的容量乘以负载因子  
  12. int threshold;  
  13. // 加载因子  
  14. final float loadFactor;  
  15. // HashMap结构修改次数,防止在遍历时,有其他的线程在进行修改  
  16. transient volatile int modCount;  
  17. public HashMap(int initialCapacity, float loadFactor) {  
  18.     if (initialCapacity < 0)  
  19.         throw new IllegalArgumentException("Illegal initial capacity: "  
  20.                 + initialCapacity);  
  21.     if (initialCapacity > MAXIMUM_CAPACITY)  
  22.         initialCapacity = MAXIMUM_CAPACITY;  
  23.     if (loadFactor <= 0 || Float.isNaN(loadFactor))  
  24.         throw new IllegalArgumentException("Illegal load factor: "  
  25.                 + loadFactor);  
  26.   
  27.     // Find a power of 2 >= initialCapacity  
  28.     int capacity = 1;  
  29.     // 使得capacity 的大小为2的幂,至于为什么,请看下面  
  30.     while (capacity < initialCapacity)  
  31.         capacity <<= 1;  
  32.   
  33.     this.loadFactor = loadFactor;  
  34.     threshold = (int) (capacity * loadFactor);  
  35.     table = new Entry[capacity];  
  36.     init();  
  37. }  

下面是用于包装key-value映射关系的Entry,它是HashMap的静态内部类: 
Java代码  收藏代码
  1. static class Entry<K, V> implements Map.Entry<K, V> {  
  2.         final K key;  
  3.         V value;  
  4.         Entry<K, V> next;  
  5.         final int hash;  
  6.   
  7.         /** 
  8.          * Creates new entry. 
  9.          */  
  10.         Entry(int h, K k, V v, Entry<K, V> n) {  
  11.             value = v;  
  12.             next = n;  
  13.             key = k;  
  14.             hash = h;  
  15.         }  
  16.   
  17.         public final K getKey() {  
  18.             return key;  
  19.         }  
  20.   
  21.         public final V getValue() {  
  22.             return value;  
  23.         }  
  24.   
  25.         public final V setValue(V newValue) {  
  26.             V oldValue = value;  
  27.             value = newValue;  
  28.             return oldValue;  
  29.         }  
  30.   
  31.         public final boolean equals(Object o) {  
  32.             if (!(o instanceof Map.Entry))  
  33.                 return false;  
  34.             Map.Entry e = (Map.Entry) o;  
  35.             Object k1 = getKey();  
  36.             Object k2 = e.getKey();  
  37.             if (k1 == k2 || (k1 != null && k1.equals(k2))) {  
  38.                 Object v1 = getValue();  
  39.                 Object v2 = e.getValue();  
  40.                 if (v1 == v2 || (v1 != null && v1.equals(v2)))  
  41.                     return true;  
  42.             }  
  43.             return false;  
  44.         }  
  45.   
  46.         public final int hashCode() {  
  47.             return (key == null ? 0 : key.hashCode())  
  48.                     ^ (value == null ? 0 : value.hashCode());  
  49.         }  
  50.   
  51.         public final String toString() {  
  52.             return getKey() + "=" + getValue();  
  53.         }  
  54.   
  55.         /** 
  56.          * This method is invoked whenever the value in an entry is overwritten 
  57.          * by an invocation of put(k,v) for a key k that's already in the 
  58.          * HashMap. 
  59.          */  
  60.         void recordAccess(HashMap<K, V> m) {  
  61.         }  
  62.   
  63.         /** 
  64.          * This method is invoked whenever the entry is removed from the table. 
  65.          */  
  66.         void recordRemoval(HashMap<K, V> m) {  
  67.         }  
  68.     }  

二、下面我们看看HashMap的put和get及remove方法源码,就知道为什么说它数据结构是链表和数组了 
Java代码  收藏代码
  1.     
  2. // 根据key获取value  
  3.     public V get(Object key) {  
  4.         if (key == null)  
  5.             return getForNullKey();  
  6.         //根据key的hashCode值计算它的hash码  
  7.         int hash = hash(key.hashCode());  
  8.         //直接取出table数组中指定索引处的值  
  9.         for (Entry<K, V> e = table[indexFor(hash, table.length)];   
  10.         e != null;   
  11.         //搜索该Entry链的下一个Entry  
  12.         e = e.next) {  
  13.             Object k;  
  14.             //如果该Entry的key与被搜索key相同  
  15.             if (e.hash == hash && ((k = e.key) == key || key.equals(k)))  
  16.                 return e.value;  
  17.         }  
  18.         return null;  
  19.     }  
  20.   
  21.     private V getForNullKey() {  
  22.         //key为null,hash码为0,也就是说key为null的Entry位于table[0]的Entry链上  
  23.         for (Entry<K, V> e = table[0]; e != null; e = e.next) {  
  24.             if (e.key == null)  
  25.                 return e.value;  
  26.         }  
  27.         return null;  
  28.     }  
  29.     public V put(K key, V value) {  
  30.         if (key == null)  
  31.             return putForNullKey(value);  
  32.         //根据key的hashCode值计算它的hash码  
  33.         int hash = hash(key.hashCode());  
  34.         //搜索指定hash值对应table中的索引值  
  35.         int i = indexFor(hash, table.length);  
  36.         for (Entry<K, V> e = table[i]; e != null; e = e.next) {  
  37.             Object k;  
  38.             //如果找到指定key与需要放入的key相等(hash值相同,通过equals比较返回true)  
  39.             if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {  
  40.                 V oldValue = e.value;  
  41.                 //新的值覆盖旧值  
  42.                 e.value = value;  
  43.                 //这个方法是个空方法,可能是表示个标记,字面意思是表示记录访问  
  44.                 e.recordAccess(this);  
  45.                 //返回旧值  
  46.                 return oldValue;  
  47.             }  
  48.         }  
  49.   
  50.         modCount++;  
  51.         //如果i处索引处的Entry为null,表示此处还没有Entry  
  52.         //将key、value添加到i索引处  
  53.         addEntry(hash, key, value, i);  
  54.         return null;  
  55.     }  
  56.   
  57.     //key=null的键值对,默认存放table[0]的Entry链  
  58.     private V putForNullKey(V value) {  
  59.         for (Entry<K, V> e = table[0]; e != null; e = e.next) {  
  60.             if (e.key == null) {  
  61.                 V oldValue = e.value;  
  62.                 e.value = value;  
  63.                 e.recordAccess(this);  
  64.                 return oldValue;  
  65.             }  
  66.         }  
  67.         modCount++;  
  68.         addEntry(0null, value, 0);  
  69.         return null;  
  70.     }  
  71.         void addEntry(int hash, K key, V value, int bucketIndex) {  
  72.         Entry<K, V> e = table[bucketIndex];  
  73.         table[bucketIndex] = new Entry<K, V>(hash, key, value, e);  
  74.         if (size++ >= threshold)  
  75.             resize(2 * table.length);  
  76.     }  
  77. //根据键值移除key-value映射对象  
  78.     public V remove(Object key) {  
  79.         Entry<K, V> e = removeEntryForKey(key);  
  80.         return (e == null ? null : e.value);  
  81.     }  
  82.   
  83.     final Entry<K, V> removeEntryForKey(Object key) {  
  84.         int hash = (key == null) ? 0 : hash(key.hashCode());  
  85.         int i = indexFor(hash, table.length);  
  86.         Entry<K, V> prev = table[i];  
  87.         Entry<K, V> e = prev;  
  88.   
  89.         while (e != null) {  
  90.             Entry<K, V> next = e.next;  
  91.             Object k;  
  92.             if (e.hash == hash  
  93.                     && ((k = e.key) == key || (key != null && key.equals(k)))) {  
  94.                 modCount++;  
  95.                 size--;  
  96.                 if (prev == e)  
  97.                     table[i] = next;  
  98.                 else  
  99.                     prev.next = next;  
  100.                 //空方法,表示移除记录  
  101.                 e.recordRemoval(this);  
  102.                 return e;  
  103.             }  
  104.             prev = e;  
  105.             e = next;  
  106.         }  
  107.   
  108.         return e;  
  109.     }  
  110.   
  111.    

三、HashMap的hash算法和size大小调整,为什么说HashMap此类不保证映射的顺序,特别是它不保证该顺序恒久不变请看以下分解: 
Java代码  收藏代码
  1.   static int hash(int h) {//这里不是很懂,得向他人请教  
  2.         // This function ensures that hashCodes that differ only by  
  3.         // constant multiples at each bit position have a bounded  
  4.         // number of collisions (approximately 8 at default load factor).  
  5.         h ^= (h >>> 20) ^ (h >>> 12);  
  6.         return h ^ (h >>> 7) ^ (h >>> 4);  
  7.     }  
  8.   
  9.     /** 
  10.      * Returns index for hash code h. 
  11.      */  
  12.     // 根据hash码求的数组小标并返回,当length为2的幂时,h & (length-1)等价于h%(length-1),这里也就是为什么前面说table的长度必须是2的幂  
  13.     static int indexFor(int h, int length) {  
  14.         return h & (length - 1);  
  15.     }  
  16. // 调整大小  
  17.     void resize(int newCapacity) {  
  18.         Entry[] oldTable = table;  
  19.         int oldCapacity = oldTable.length;  
  20.         if (oldCapacity == MAXIMUM_CAPACITY) {  
  21.             threshold = Integer.MAX_VALUE;  
  22.             return;  
  23.         }  
  24.   
  25.         Entry[] newTable = new Entry[newCapacity];  
  26.         transfer(newTable);  
  27.         table = newTable;  
  28.         threshold = (int) (newCapacity * loadFactor);  
  29.     }  
  30.   
  31.     /** 
  32.      * Transfers all entries from current table to newTable. 
  33.      */  
  34.     void transfer(Entry[] newTable) {  
  35.         Entry[] src = table;  
  36.         int newCapacity = newTable.length;  
  37.         for (int j = 0; j < src.length; j++) {  
  38.             Entry<K, V> e = src[j];  
  39.             if (e != null) {  
  40.                 src[j] = null;  
  41.                 do {      
  42.                                         //注意这里哈,HashMap不保证顺序恒久不变  
  43.                                         //在这里可以找到答案  
  44.                     Entry<K, V> next = e.next;  
  45.                     int i = indexFor(e.hash, newCapacity);  
  46.                     e.next = newTable[i];  
  47.                     newTable[i] = e;  
  48.                     e = next;  
  49.                 } while (e != null);  
  50.             }  
  51.         }  
  52.     }  

四、HashMap与Set的关系,Set代表一种集合元素无序、集合元素不可重复的集合。如果只考察HashMap中的key,不难发现集合中的key有一个特征:所有的key不能重复,key之间无序。具备了Set的特征,所有的key集合起来组成一个Set集合。同理所有的Entry集合起来,也是一个Set集合。而value是可以重复的,不能组成一个Set集合,在HashMap源代码中提供了values()方法把value集合起来组成Collection集合。 
Java代码  收藏代码
  1. private abstract class HashIterator<E> implements Iterator<E> {  
  2.     Entry<K, V> next; // next entry to return  
  3.     int expectedModCount; // For fast-fail  
  4.     int index; // current slot  
  5.     Entry<K, V> current; // current entry  
  6.   
  7.     HashIterator() {  
  8.         expectedModCount = modCount;  
  9.         if (size > 0) { // advance to first entry  
  10.             Entry[] t = table;  
  11.             while (index < t.length && (next = t[index++]) == null)  
  12.                 ;  
  13.         }  
  14.     }  
  15.   
  16.     public final boolean hasNext() {  
  17.         return next != null;  
  18.     }  
  19.   
  20.     final Entry<K, V> nextEntry() {  
  21.         if (modCount != expectedModCount)  
  22.             throw new ConcurrentModificationException();  
  23.         Entry<K, V> e = next;  
  24.         if (e == null)  
  25.             throw new NoSuchElementException();  
  26.   
  27.         if ((next = e.next) == null) {  
  28.             Entry[] t = table;  
  29.             while (index < t.length && (next = t[index++]) == null)  
  30.                 ;  
  31.         }  
  32.         current = e;  
  33.         return e;  
  34.     }  
  35.   
  36.     public void remove() {  
  37.         if (current == null)  
  38.             throw new IllegalStateException();  
  39.         if (modCount != expectedModCount)  
  40.             throw new ConcurrentModificationException();  
  41.         Object k = current.key;  
  42.         current = null;  
  43.         HashMap.this.removeEntryForKey(k);  
  44.         expectedModCount = modCount;  
  45.     }  
  46.   
  47. }  
  48.     private final class ValueIterator extends HashIterator<V> {  
  49.     public V next() {  
  50.         return nextEntry().value;  
  51.     }  
  52. }  
  53.   
  54. private final class KeyIterator extends HashIterator<K> {  
  55.     public K next() {  
  56.         return nextEntry().getKey();  
  57.     }  
  58. }  
  59.   
  60. private final class EntryIterator extends HashIterator<Map.Entry<K, V>> {  
  61.     public Map.Entry<K, V> next() {  
  62.         return nextEntry();  
  63.     }  
  64. }  
  65. Iterator<K> newKeyIterator() {  
  66.     return new KeyIterator();  
  67. }  
  68. Iterator<V> newValueIterator() {  
  69.     return new ValueIterator();  
  70. }  
  71. Iterator<Map.Entry<K, V>> newEntryIterator() {  
  72.     return new EntryIterator();  
  73. }  
  74. // Views  
  75.   
  76. private transient Set<Map.Entry<K, V>> entrySet = null;  
  77.  //把所有的key集合成Set集合  
  78. public Set<K> keySet() {  
  79.     Set<K> ks = keySet;  
  80.     return (ks != null ? ks : (keySet = new KeySet()));  
  81. }  
  82.   
  83. private final class KeySet extends AbstractSet<K> {  
  84.     public Iterator<K> iterator() {  
  85.         return newKeyIterator();  
  86.     }  
  87.   
  88.     public int size() {  
  89.         return size;  
  90.     }  
  91.   
  92.     public boolean contains(Object o) {  
  93.         return containsKey(o);  
  94.     }  
  95.   
  96.     public boolean remove(Object o) {  
  97.         return HashMap.this.removeEntryForKey(o) != null;  
  98.     }  
  99.   
  100.     public void clear() {  
  101.         HashMap.this.clear();  
  102.     }  
  103. }  
  104.    //把所有的values集合成Collection集合  
  105. public Collection<V> values() {  
  106.     Collection<V> vs = values;  
  107.     return (vs != null ? vs : (values = new Values()));  
  108. }  
  109.   
  110. private final class Values extends AbstractCollection<V> {  
  111.     public Iterator<V> iterator() {  
  112.         return newValueIterator();  
  113.     }  
  114.     public int size() {  
  115.         return size;  
  116.     }  
  117.     public boolean contains(Object o) {  
  118.         return containsValue(o);  
  119.     }  
  120.   
  121.     public void clear() {  
  122.         HashMap.this.clear();  
  123.     }  
  124. }  
  125.   //把所有的Entry对象集合成Set集合  
  126. public Set<Map.Entry<K, V>> entrySet() {  
  127.     return entrySet0();  
  128. }  
  129.   
  130. private Set<Map.Entry<K, V>> entrySet0() {  
  131.     Set<Map.Entry<K, V>> es = entrySet;  
  132.     return es != null ? es : (entrySet = new EntrySet());  
  133. }  
  134.   
  135. private final class EntrySet extends AbstractSet<Map.Entry<K, V>> {  
  136.     public Iterator<Map.Entry<K, V>> iterator() {  
  137.         return newEntryIterator();  
  138.     }  
  139.     public boolean contains(Object o) {  
  140.         if (!(o instanceof Map.Entry))  
  141.             return false;  
  142.         Map.Entry<K, V> e = (Map.Entry<K, V>) o;  
  143.         Entry<K, V> candidate = getEntry(e.getKey());  
  144.         return candidate != null && candidate.equals(e);  
  145.     }  
  146.     public boolean remove(Object o) {  
  147.         return removeMapping(o) != null;  
  148.     }  
  149.     public int size() {  
  150.         return size;  
  151.     }  
  152.     public void clear() {  
  153.         HashMap.this.clear();  
  154.     }  
  155. }  

五、fail-fast策略(速错)HashMap不是线程安全的,因此如果在使用迭代器的过程中有其他线程修改了map,那么将抛ConcurrentModificationException,这就是所谓fail-fast策略(速错),这一策略在源码中的实现是通过modCount域,modCount顾名思义就是修改次数,对HashMap内容的修改都将增加这个值,那么在迭代器初始化过程中会将这个值赋给迭代器的expectedModCount。在迭代过程中,判断modCount跟expectedModCount是否相等,如果不相等就表示已经有其他线程修改了 
Java代码  收藏代码
  1. private abstract class HashIterator<E> implements Iterator<E> {  
  2.         Entry<K, V> next; // next entry to return  
  3.         int expectedModCount; // For fast-fail  
  4.         int index; // current slot  
  5.         Entry<K, V> current; // current entry  
  6.   
  7.         HashIterator() {  
  8.             expectedModCount = modCount;  
  9.             if (size > 0) { // advance to first entry  
  10.                 Entry[] t = table;  
  11.                 while (index < t.length && (next = t[index++]) == null)  
  12.                     ;  
  13.             }  
  14.         }  
  15.   
  16.         public final boolean hasNext() {  
  17.             return next != null;  
  18.         }  
  19.   
  20.         final Entry<K, V> nextEntry() {  
  21.             if (modCount != expectedModCount)  
  22.                 throw new ConcurrentModificationException();  
  23.             Entry<K, V> e = next;  
  24.             if (e == null)  
  25.                 throw new NoSuchElementException();  
  26.   
  27.             if ((next = e.next) == null) {  
  28.                 Entry[] t = table;  
  29.                 while (index < t.length && (next = t[index++]) == null)  
  30.                     ;  
  31.             }  
  32.             current = e;  
  33.             return e;  
  34.         }  
  35.   
  36.         public void remove() {  
  37.             if (current == null)  
  38.                 throw new IllegalStateException();  
  39.             if (modCount != expectedModCount)  
  40.                 throw new ConcurrentModificationException();  
  41.             Object k = current.key;  
  42.             current = null;  
  43.             HashMap.this.removeEntryForKey(k);  
  44.             expectedModCount = modCount;  
  45.         }  
  46.   
  47.     }  
原创粉丝点击