HashMap源码分析和应用实例的介绍

1、HashMap介绍

HashMap 是一个散列表,它存储的内容是键值对(key-value)映射。
HashMap 继承于AbstractMap,实现了Map、Cloneable、java.io.Serializable接口。
HashMap 的实现不是同步的,这意味着它不是线程安全的。它的key、value都可以为null。此外,HashMap中的映射不是有序的

HashMap 的实例有两个参数影响其性能:“初始容量” 和 “加载因子”。容量 是哈希表中桶的数量,初始容量只是哈希表在创建时的容量。加载因子 是哈希表在其容量自动增加之前可以达到多满的一种尺度。当哈希表中的条目数超出了加载因子与当前容量的乘积时,则要对该哈希表进行 rehash 操作(即重建内部数据结构),从而哈希表将具有大约两倍的桶数。通常,默认加载因子是 0.75, 这是在时间和空间成本上寻求一种折中。加载因子过高虽然降低了空间成本的开销,但同时也增加了查询成本(在大多数 HashMap 类的操作中,包括 get 和 put 操作,都反映了这一点)。在设置初始容量时应该考虑到映射中所需的条目数及其加载因子,以便最大限度地减少 rehash 操作次数。如果初始容量大于最大条目数除以加载因子,则不会发生 rehash 操作。

 1 // 默认构造函数。
 2 HashMap()
 3 
 4 // 指定“容量大小”的构造函数
 5 HashMap(int capacity)
 6 
 7 // 指定“容量大小”和“加载因子”的构造函数
 8 HashMap(int capacity, float loadFactor)
 9 
10 // 包含“子Map”的构造函数
11 HashMap(Map<? extends K, ? extends V> map)

2、HashMap数据结构

2.1、HashMap的继承关系

1 java.lang.Object
2    ↳     java.util.AbstractMap<K, V>
3          ↳     java.util.HashMap<K, V>
4 
5 public class HashMap<K,V>
6     extends AbstractMap<K,V>
7     implements Map<K,V>, Cloneable, Serializable { }

2.2、HashMap的继承关系图

从图中可以看出:
(01) HashMap继承于AbstractMap类,实现了Map接口。Map是"key-value键值对"接口,AbstractMap实现了"键值对"的通用函数接口。
(02) HashMap是通过"拉链法"实现的哈希表。它包括几个重要的成员变量:table, size, threshold, loadFactor, modCount。

  • table是一个Entry[]类型的数组,而Entry实际上就是一个单向链表。哈希表的"key-value键值对"都是存储在Entry数组中的。
  • size是HashMap中存储元素的实际大小,它是HashMap保存的键值对的数量。
  • threshold是HashMap的阈值,用于判断是否需要调整HashMap的容量。threshold的值="容量*加载因子",当HashMap中存储数据的数量达到threshold时,就需要将HashMap的容量加倍。
  • loadFactor就是加载因子。
  • modCount是用来实现fail-fast机制的。

3、HashMap源码分析

  1 package java.util;
  2 import java.io.*;
  3 
  4 public class HashMap<K,V>
  5     extends AbstractMap<K,V>
  6     implements Map<K,V>, Cloneable, Serializable
  7 {
  8 
  9     // 默认的初始容量是16,容量的大小必须是2的幂。
 10     static final int DEFAULT_INITIAL_CAPACITY = 16;
 11 
 12     // 最大容量(必须是2的幂且小于2的30次方,如果传入的容量过大将会用这个值来替换传入的值)
 13     static final int MAXIMUM_CAPACITY = 1 << 30;
 14 
 15     // 默认加载因子
 16     static final float DEFAULT_LOAD_FACTOR = 0.75f;
 17 
 18     // 存储数据的Entry数组,长度是2的幂。
 19     // HashMap是采用拉链法实现的,每一个Entry本质上就是一个单向链表
 20     transient Entry[] table;
 21 
 22     // HashMap的大小,它是HashMap保存的键值对的数量
 23     transient int size;
 24 
 25     // HashMap的阈值,用于判断是否需要调整HashMap的容量(threshold = 容量*加载因子)
 26     int threshold;
 27 
 28     // 加载因子实际大小
 29     final float loadFactor;
 30 
 31     // HashMap被改变的次数,用来实现fail-fast机制的
 32     transient volatile int modCount;
 33 
 34     // 指定“容量大小”和“加载因子”的构造函数
 35     public HashMap(int initialCapacity, float loadFactor) {
 36         //先判断输入的容量大小是否非法
 37         if (initialCapacity < 0)
 38             throw new IllegalArgumentException("Illegal initial capacity: " +
 39                                                initialCapacity);
 40         // HashMap的最大容量只能是MAXIMUM_CAPACITY
 41         //如果传入的容量过大将会用这个值来替换传入的值
 42         if (initialCapacity > MAXIMUM_CAPACITY)
 43             initialCapacity = MAXIMUM_CAPACITY;
 44         if (loadFactor <= 0 || Float.isNaN(loadFactor))
 45             throw new IllegalArgumentException("Illegal load factor: " +
 46                                                loadFactor);
 47 
 48         // 找出“大于initialCapacity”的最小的2的幂,这样做保证容量的大小是2的幂指数,因为传入的容量大小不一定是2的幂指数
 49         int capacity = 1;
 50         while (capacity < initialCapacity)
 51             capacity <<= 1;
 52 
 53         // 设置“加载因子”
 54         this.loadFactor = loadFactor;
 55         // 设置“HashMap阈值”,当HashMap中存储数据的数量达到threshold时,就需要将HashMap的容量加倍。
 56         threshold = (int)(capacity * loadFactor);
 57         // 创建Entry数组,用来保存数据
 58         table = new Entry[capacity];
 59         init();
 60     }
 61 
 62 
 63     // 指定“容量大小”的构造函数
 64     public HashMap(int initialCapacity) {
 65         this(initialCapacity, DEFAULT_LOAD_FACTOR);
 66     }
 67 
 68     // 默认构造函数。默认的情况下所有参数都是使用的默认,这样当数据量较小的时候容易造成资源的浪费
 69     public HashMap() {
 70         // 设置“加载因子”
 71         this.loadFactor = DEFAULT_LOAD_FACTOR;
 72         // 设置“HashMap阈值”,当HashMap中存储数据的数量达到threshold时,就需要将HashMap的容量加倍。
 73         threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
 74         // 创建Entry数组,用来保存数据
 75         table = new Entry[DEFAULT_INITIAL_CAPACITY];
 76         init();
 77     }
 78 
 79     // 包含“子Map集合”的构造函数
 80     public HashMap(Map<? extends K, ? extends V> m) {
 81         this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
 82                       DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
 83         // 将m中的全部元素逐个添加到HashMap中
 84         putAllForCreate(m);
 85     }
 86     //自定义的hash函数
 87     static int hash(int h) {
 88         h ^= (h >>> 20) ^ (h >>> 12);
 89         return h ^ (h >>> 7) ^ (h >>> 4);
 90     }
 91 
 92     // 返回索引值
 93     // h & (length-1)能够确保返回值的大小都小于length
 94     static int indexFor(int h, int length) {
 95         return h & (length-1);
 96     }
 97 
 98     public int size() {
 99         return size;
100     }
101 
102     public boolean isEmpty() {
103         return size == 0;
104     }
105 
106     // 获取key对应的value
107     public V get(Object key) {
108         //从中可以看出key的值允许为null
109         if (key == null)
110             return getForNullKey();
111         // 获取key的hash值:key是一个Object对象,调用该对象的hashCode()函数然后再通过自定义的hash函数得出该对象的hash值。
112         int hash = hash(key.hashCode());
113         // 在“该hash值对应的链表”上查找“键值等于key”的元素
114         for (Entry<K,V> e = table[indexFor(hash, table.length)];
115              e != null;
116              e = e.next) {
117             Object k;
118             //这里的比较条件是key的hash值相等且key的值也相等
119             if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
120                 return e.value;
121         }
122         return null;
123     }
124 
125     // 获取“key为null”的元素的值
126     // 这是规定好的:HashMap将“key为null”的元素存储在table[0]位置。且只能存储一个key-value键值对。
127     private V getForNullKey() {
128         for (Entry<K,V> e = table[0]; e != null; e = e.next) {
129             if (e.key == null)
130                 return e.value;
131         }
132         return null;
133     }
134 
135     // HashMap集合中判断是否包含key
136     public boolean containsKey(Object key) {
137         return getEntry(key) != null;
138     }
139 
140     // 返回“键为key”的键值对
141     final Entry<K,V> getEntry(Object key) {
142         // 获取哈希值
143         // HashMap将“key为null”的元素存储在table[0]位置,“key不为null”的则调用hash()计算哈希值
144         int hash = (key == null) ? 0 : hash(key.hashCode());
145         // 在“该hash值对应的链表”上查找“键值等于key”的元素
146         for (Entry<K,V> e = table[indexFor(hash, table.length)];
147              e != null;
148              e = e.next) {
149             Object k;
150             if (e.hash == hash &&
151                 ((k = e.key) == key || (key != null && key.equals(k))))
152                 return e;
153         }
154         return null;
155     }
156 
157     // 将“key-value”添加到HashMap中
158     public V put(K key, V value) {
159         // 若“key为null”,则将该键值对添加到table[0]中。
160         if (key == null)
161             return putForNullKey(value);
162         // 若“key不为null”,则计算该key的哈希值,然后将其添加到该哈希值对应的链表中。
163         int hash = hash(key.hashCode());
164         int i = indexFor(hash, table.length);
165         for (Entry<K,V> e = table[i]; e != null; e = e.next) {
166             Object k;
167             // 若“该key”对应的键值对已经存在,则用新的value取代旧的value。然后退出!
168             if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
169                 V oldValue = e.value;
170                 e.value = value;
171                 e.recordAccess(this);
172                 return oldValue;
173             }
174         }
175 
176         // 若“该key”对应的键值对不存在,则将“key-value”添加到table中
177         modCount++;
178         addEntry(hash, key, value, i);
179         return null;
180     }
181 
182     // putForNullKey()的作用是将“key为null”键值对添加到table[0]位置
183     private V putForNullKey(V value) {
184         for (Entry<K,V> e = table[0]; e != null; e = e.next) {
185             if (e.key == null) {
186                 V oldValue = e.value;
187                 e.value = value;
188                 e.recordAccess(this);
189                 return oldValue;
190             }
191         }
192         // 这里的完全不会被执行到!
193         modCount++;
194         addEntry(0, null, value, 0);
195         return null;
196     }
197 
198     // 创建HashMap对应的“添加方法”,
199     // 它和put()不同。putForCreate()是内部方法,它被构造函数等调用,用来创建HashMap
200     // 而put()是对外提供的往HashMap中添加元素的方法。
201     private void putForCreate(K key, V value) {
202         int hash = (key == null) ? 0 : hash(key.hashCode());
203         int i = indexFor(hash, table.length);
204 
205         // 若该HashMap表中存在“键值等于key”的元素,则替换该元素的value值
206         for (Entry<K,V> e = table[i]; e != null; e = e.next) {
207             Object k;
208             if (e.hash == hash &&
209                 ((k = e.key) == key || (key != null && key.equals(k)))) {
210                 e.value = value;
211                 return;
212             }
213         }
214 
215         // 若该HashMap表中不存在“键值等于key”的元素,则将该key-value添加到HashMap中
216         createEntry(hash, key, value, i);
217     }
218 
219     // 将“m”中的全部元素都添加到HashMap中。
220     // 该方法被内部的构造HashMap的方法所调用。
221     private void putAllForCreate(Map<? extends K, ? extends V> m) {
222         // 利用迭代器将元素逐个添加到HashMap中
223         for (Iterator<? extends Map.Entry<? extends K, ? extends V>> i = m.entrySet().iterator(); i.hasNext(); ) {
224             Map.Entry<? extends K, ? extends V> e = i.next();
225             putForCreate(e.getKey(), e.getValue());
226         }
227     }
228 
229     // 重新调整HashMap的大小,newCapacity是调整后的单位
230     void resize(int newCapacity) {
231         Entry[] oldTable = table;
232         int oldCapacity = oldTable.length;
233         if (oldCapacity == MAXIMUM_CAPACITY) {
234             threshold = Integer.MAX_VALUE;
235             return;
236         }
237 
238         // 新建一个HashMap,将“旧HashMap”的全部元素添加到“新HashMap”中,
239         // 然后,将“新HashMap”赋值给“旧HashMap”。
240         Entry[] newTable = new Entry[newCapacity];
241         transfer(newTable);
242         table = newTable;
243         threshold = (int)(newCapacity * loadFactor);
244     }
245 
246     // 将HashMap中的全部元素都添加到newTable中
247     void transfer(Entry[] newTable) {
248         Entry[] src = table;
249         int newCapacity = newTable.length;
250         for (int j = 0; j < src.length; j++) {
251             Entry<K,V> e = src[j];
252             if (e != null) {
253                 src[j] = null;
254                 do {
255                     Entry<K,V> next = e.next;
256                     int i = indexFor(e.hash, newCapacity);
257                     e.next = newTable[i];
258                     newTable[i] = e;
259                     e = next;
260                 } while (e != null);
261             }
262         }
263     }
264 
265     // 将"m"的全部元素都添加到HashMap中
266     public void putAll(Map<? extends K, ? extends V> m) {
267         // 有效性判断
268         int numKeysToBeAdded = m.size();
269         if (numKeysToBeAdded == 0)
270             return;
271 
272         // 计算容量是否足够,
273         // 若“当前实际容量 < 需要的容量”,则将容量x2。
274         if (numKeysToBeAdded > threshold) {
275             int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
276             if (targetCapacity > MAXIMUM_CAPACITY)
277                 targetCapacity = MAXIMUM_CAPACITY;
278             int newCapacity = table.length;
279             while (newCapacity < targetCapacity)
280                 newCapacity <<= 1;
281             if (newCapacity > table.length)
282                 resize(newCapacity);
283         }
284 
285         // 通过迭代器,将“m”中的元素逐个添加到HashMap中。
286         for (Iterator<? extends Map.Entry<? extends K, ? extends V>> i = m.entrySet().iterator(); i.hasNext(); ) {
287             Map.Entry<? extends K, ? extends V> e = i.next();
288             put(e.getKey(), e.getValue());
289         }
290     }
291 
292     // 删除“键为key”元素
293     public V remove(Object key) {
294         Entry<K,V> e = removeEntryForKey(key);
295         return (e == null ? null : e.value);
296     }
297 
298     // 删除“键为key”的元素
299     final Entry<K,V> removeEntryForKey(Object key) {
300         // 获取哈希值。若key为null,则哈希值为0;否则调用hash()进行计算
301         int hash = (key == null) ? 0 : hash(key.hashCode());
302         int i = indexFor(hash, table.length);
303         //变量prev指的是当前待删除元素的前一个元素
304         Entry<K,V> prev = table[i];
305         //变量e指的是当前待删除的元素
306         Entry<K,V> e = prev;
307 
308         // 删除链表中“键为key”的元素
309         // 本质是“删除单向链表中的节点”
310         while (e != null) {
311             Entry<K,V> next = e.next;
312             Object k;
313             if (e.hash == hash &&
314                 ((k = e.key) == key || (key != null && key.equals(k)))) {
315                 modCount++;
316                 size--;
317                 //当删除的是单链表中第一个元素的时候
318                 if (prev == e)
319                     table[i] = next;
320                 else
321                     //当删除的是单链表中非第一个元素的时候
322                     prev.next = next;
323                 e.recordRemoval(this);
324                 return e;
325             }
326             prev = e;
327             e = next;
328         }
329 
330         return e;
331     }
332 
333     // 删除“键值对”
334     final Entry<K,V> removeMapping(Object o) {
335         if (!(o instanceof Map.Entry))
336             return null;
337 
338         Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
339         Object key = entry.getKey();
340         int hash = (key == null) ? 0 : hash(key.hashCode());
341         int i = indexFor(hash, table.length);
342         Entry<K,V> prev = table[i];
343         Entry<K,V> e = prev;
344 
345         // 删除链表中的“键值对e”
346         // 本质是“删除单向链表中的节点”
347         while (e != null) {
348             Entry<K,V> next = e.next;
349             if (e.hash == hash && e.equals(entry)) {
350                 modCount++;
351                 size--;
352                 if (prev == e)
353                     table[i] = next;
354                 else
355                     prev.next = next;
356                 e.recordRemoval(this);
357                 return e;
358             }
359             prev = e;
360             e = next;
361         }
362 
363         return e;
364     }
365 
366     // 清空HashMap,将所有的元素设为null
367     public void clear() {
368         modCount++;
369         Entry[] tab = table;
370         //清空hashMap就是要把Entry[]数组中每一个单链表全部赋值为空,并且把元素个数赋值为0
371         for (int i = 0; i < tab.length; i++)
372             tab[i] = null;
373         size = 0;
374     }
375 
376     // 是否包含“值为value”的元素
377     public boolean containsValue(Object value) {
378     // 若“value为null”,则调用containsNullValue()查找
379     if (value == null)
380             return containsNullValue();
381     // 若“value不为null”,则查找HashMap中是否有值为value的节点。
382     Entry[] tab = table;
383         for (int i = 0; i < tab.length ; i++)
384             for (Entry e = tab[i] ; e != null ; e = e.next)
385                 if (value.equals(e.value))
386                     return true;
387     return false;
388     }
389 
390     // 是否包含null值
391     private boolean containsNullValue() {
392     Entry[] tab = table;
393         for (int i = 0; i < tab.length ; i++)
394             for (Entry e = tab[i] ; e != null ; e = e.next)
395                 if (e.value == null)
396                     return true;
397     return false;
398     }
399 
400     // 克隆一个HashMap,并返回Object对象
401     public Object clone() {
402         HashMap<K,V> result = null;
403         try {
404             result = (HashMap<K,V>)super.clone();
405         } catch (CloneNotSupportedException e) {
406             // assert false;
407         }
408         result.table = new Entry[table.length];
409         result.entrySet = null;
410         result.modCount = 0;
411         result.size = 0;
412         result.init();
413         // 调用putAllForCreate()将全部元素添加到HashMap中
414         result.putAllForCreate(this);
415         return result;
416     }
417     //静态内部类
418     // Entry是单向链表。
419     // 它是 “HashMap链式存储法”对应的链表。
420     // 它实现了Map.Entry 接口,即实现getKey(), getValue(), setValue(V value), equals(Object o), hashCode()这些函数
421     static class Entry<K,V> implements Map.Entry<K,V> {
422         final K key;
423         V value;
424         // 指向下一个节点
425         Entry<K,V> next;
426         final int hash;
427 
428         // 构造函数。
429         // 输入参数包括"哈希值(h)", "键(k)", "值(v)", "下一节点(n)"
430         Entry(int h, K k, V v, Entry<K,V> n) {
431             value = v;
432             next = n;
433             key = k;
434             hash = h;
435         }
436     //常用的get、set方法
437         public final K getKey() {
438             return key;
439         }
440 
441         public final V getValue() {
442             return value;
443         }
444 
445         public final V setValue(V newValue) {
446             V oldValue = value;
447             value = newValue;
448             return oldValue;
449         }
450        //    重写equals方法
451         // 判断两个Entry是否相等
452         // 若两个Entry的“key”和“value”都相等的情况下,才会返回true。
453         // 否则,返回false
454         public final boolean equals(Object o) {
455             if (!(o instanceof Map.Entry))
456                 return false;
457             Map.Entry e = (Map.Entry)o;
458             Object k1 = getKey();
459             Object k2 = e.getKey();
460             if (k1 == k2 || (k1 != null && k1.equals(k2))) {
461                 Object v1 = getValue();
462                 Object v2 = e.getValue();
463                 if (v1 == v2 || (v1 != null && v1.equals(v2)))
464                     return true;
465             }
466             return false;
467         }
468 
469         // 重写hashCode()方法
470         public final int hashCode() {
471             return (key==null   ? 0 : key.hashCode()) ^
472                    (value==null ? 0 : value.hashCode());
473         }
474         // 重写toString()方法
475         public final String toString() {
476             return getKey() + "=" + getValue();
477         }
478 
479         // 当向HashMap中添加元素时,虽然会调用recordAccess()。
480         // 但是源代码在这里没有做任何处理
481         void recordAccess(HashMap<K,V> m) {
482         }
483       // 当向HashMap中添加元素时,虽然会调用recordRemoval()。
484         // 但是源代码在这里没有做任何处理
485         void recordRemoval(HashMap<K,V> m) {
486         }
487     }
488     // 新增Entry。将“key-value”插入指定位置,bucketIndex是位置索引。
489     void addEntry(int hash, K key, V value, int bucketIndex) {
490         // 保存“bucketIndex”位置的值到“e”中
491         Entry<K,V> e = table[bucketIndex];
492         // 设置“bucketIndex”位置的元素为“新Entry”,
493         // 调用构造器先创建一个新Entry节点,并设置“e”为“新创建Entry的下一个节点”
494         table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
495         // 若HashMap的实际大小 不小于 “阈值”,则调整HashMap的大小
496         if (size++ >= threshold)
497             resize(2 * table.length);
498     }
499 
500     // 创建Entry。将“key-value”插入指定位置,bucketIndex是位置索引。
501     // 它和addEntry的区别是:
502     // (01) addEntry()一般用在 新增Entry可能导致“HashMap的实际容量”超过“阈值”的情况下。
503     //   例如,我们新建一个HashMap,然后不断通过put()向HashMap中添加元素;
504     // put()函数中是通过addEntry()函数不断地新增Entry节点的。
505     //   在这种情况下,我们不知道何时“HashMap的实际容量”会超过“阈值”;
506     //   因此,需要调用addEntry()
507     // (02) createEntry() 一般用在 新增Entry不会导致“HashMap的实际容量”超过“阈值”的情况下。这个不会超过是事先已经确定好容量的打消了
508     //   例如,我们调用HashMap“带有Map”的构造函数,构造函数会将Map的全部元素添加到HashMap中;
509     // 但在添加之前,我们已经计算好“HashMap的容量和阈值”。也就是,可以确定“即使将Map中
510     // 的全部元素添加到HashMap中,都不会超过HashMap的阈值”。
511     //   此时,调用createEntry()即可。
512     void createEntry(int hash, K key, V value, int bucketIndex) {
513         // 保存“bucketIndex”位置的值到“e”中
514         Entry<K,V> e = table[bucketIndex];
515         // 设置“bucketIndex”位置的元素为“新Entry”,
516         // 设置“e”为“新Entry的下一个节点”
517         table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
518         size++;
519     }
520 
521     // HashIterator是HashMap迭代器抽象出来的父类,实现了公共了函数,实现了Iterator接口。
522     // 它包含“key迭代器(KeyIterator)”、“Value迭代器(ValueIterator)”和“Entry迭代器(EntryIterator)”3个子类。
523     private abstract class HashIterator<E> implements Iterator<E> {
524         // 下一个元素
525         Entry<K,V> next;
526         // expectedModCount用于实现fast-fail机制。
527         int expectedModCount;
528         // 当前索引
529         int index;
530         // 当前元素
531         Entry<K,V> current;
532 
533         HashIterator() {
534             expectedModCount = modCount;
535             if (size > 0) { // advance to first entry
536                 Entry[] t = table;
537                 // 将next指向table中第一个不为null的元素。
538                 // 这里利用了index的初始值为0,从0开始依次向后遍历,直到找到不为null的元素就退出循环。
539                 while (index < t.length && (next = t[index++]) == null)
540                     ;
541             }
542         }
543 
544         public final boolean hasNext() {
545             return next != null;
546         }
547 
548         // 获取下一个元素
549         final Entry<K,V> nextEntry() {
550             if (modCount != expectedModCount)
551                 throw new ConcurrentModificationException();
552             Entry<K,V> e = next;
553             if (e == null)
554                 throw new NoSuchElementException();
555 
556             // 注意!!!
557             // 一个Entry就是一个单向链表
558             // 若该Entry的下一个节点不为空,就将next指向下一个节点;
559             // 若该Entry的下一个节点为空,将next指针指向下一个Entry数组(也是下一个Entry)的不为null的节点。
560             if ((next = e.next) == null) {
561                 Entry[] t = table;
562                 while (index < t.length && (next = t[index++]) == null)
563                     ;
564             }
565             current = e;
566             return e;
567         }
568 
569         // 删除当前元素
570         public void remove() {
571             if (current == null)
572                 throw new IllegalStateException();
573             if (modCount != expectedModCount)
574                 throw new ConcurrentModificationException();
575             Object k = current.key;
576             current = null;
577             HashMap.this.removeEntryForKey(k);
578             expectedModCount = modCount;
579         }
580 
581     }
582 
583     // value的迭代器,继承于HashIterator迭代器
584     private final class ValueIterator extends HashIterator<V> {
585         public V next() {
586             //调用的是父类的nextEntry()函数
587             return nextEntry().value;
588         }
589     }
590 
591     // key的迭代器,继承于HashIterator迭代器
592     private final class KeyIterator extends HashIterator<K> {
593         public K next() {
594             //调用的是父类的nextEntry()函数
595             return nextEntry().getKey();
596         }
597     }
598 
599     // Entry的迭代器,继承于HashIterator迭代器
600     private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
601         public Map.Entry<K,V> next() {
602             //调用的是父类的nextEntry()函数
603             return nextEntry();
604         }
605     }
606 
607     // 返回一个“key迭代器”
608     Iterator<K> newKeyIterator()   {
609         return new KeyIterator();
610     }
611     // 返回一个“value迭代器”
612     Iterator<V> newValueIterator()   {
613         return new ValueIterator();
614     }
615     // 返回一个“entry迭代器”
616     Iterator<Map.Entry<K,V>> newEntryIterator()   {
617         return new EntryIterator();
618     }
619 
620     // HashMap的Entry对应的集合
621     private transient Set<Map.Entry<K,V>> entrySet = null;
622 
623     // 返回“key的集合”,实际上返回一个“KeySet对象”
624     public Set<K> keySet() {
625         Set<K> ks = keySet;
626         return (ks != null ? ks : (keySet = new KeySet()));
627     }
628 
629     // Key对应的集合
630     // KeySet继承于AbstractSet,说明该集合中没有重复的Key。
631     private final class KeySet extends AbstractSet<K> {
632         public Iterator<K> iterator() {
633             return newKeyIterator();
634         }
635         public int size() {
636             return size;
637         }
638         public boolean contains(Object o) {
639             return containsKey(o);
640         }
641         public boolean remove(Object o) {
642             return HashMap.this.removeEntryForKey(o) != null;
643         }
644         public void clear() {
645             HashMap.this.clear();
646         }
647     }
648 
649     // 返回“value集合”,实际上返回的是一个Values对象
650     public Collection<V> values() {
651         Collection<V> vs = values;
652         return (vs != null ? vs : (values = new Values()));
653     }
654 
655     // “value集合”
656     // Values继承于AbstractCollection,不同于“KeySet继承于AbstractSet”,
657     // Values中的元素能够重复。因为不同的key可以指向相同的value。
658     private final class Values extends AbstractCollection<V> {
659         public Iterator<V> iterator() {
660             return newValueIterator();
661         }
662         public int size() {
663             return size;
664         }
665         public boolean contains(Object o) {
666             return containsValue(o);
667         }
668         public void clear() {
669             HashMap.this.clear();
670         }
671     }
672 
673     // 返回“HashMap的Entry集合”
674     public Set<Map.Entry<K,V>> entrySet() {
675         return entrySet0();
676     }
677 
678     // 返回“HashMap的Entry集合”,它实际是返回一个EntrySet对象
679     private Set<Map.Entry<K,V>> entrySet0() {
680         Set<Map.Entry<K,V>> es = entrySet;
681         return es != null ? es : (entrySet = new EntrySet());
682     }
683 
684     // EntrySet对应的集合
685     // EntrySet继承于AbstractSet,说明该集合中没有重复的EntrySet。
686     private final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
687         public Iterator<Map.Entry<K,V>> iterator() {
688             return newEntryIterator();
689         }
690         public boolean contains(Object o) {
691             if (!(o instanceof Map.Entry))
692                 return false;
693             Map.Entry<K,V> e = (Map.Entry<K,V>) o;
694             Entry<K,V> candidate = getEntry(e.getKey());
695             return candidate != null && candidate.equals(e);
696         }
697         public boolean remove(Object o) {
698             return removeMapping(o) != null;
699         }
700         public int size() {
701             return size;
702         }
703         public void clear() {
704             HashMap.this.clear();
705         }
706     }
707 
708     // java.io.Serializable的写入函数
709     // 将HashMap的“总的容量,实际容量,所有的Entry”都写入到输出流中
710     private void writeObject(java.io.ObjectOutputStream s)
711         throws IOException
712     {
713         Iterator<Map.Entry<K,V>> i =
714             (size > 0) ? entrySet0().iterator() : null;
715         // Write out the threshold, loadfactor, and any hidden stuff
716         s.defaultWriteObject();
717        //先写数组的长度
718         s.writeInt(table.length);
719         // 再写数据元素的大小
720         s.writeInt(size);
721         // 然后再把一个一个的元素写进输出流对象中
722         if (i != null) {
723             while (i.hasNext()) {
724             Map.Entry<K,V> e = i.next();
725             s.writeObject(e.getKey());
726             s.writeObject(e.getValue());
727             }
728         }
729     }
730     private static final long serialVersionUID = 362498820763181265L;
731     // java.io.Serializable的读取函数:根据写入方式读出
732     // 将HashMap的“总的容量,实际容量,所有的Entry”依次读出
733     private void readObject(java.io.ObjectInputStream s)
734          throws IOException, ClassNotFoundException
735     {
736         // Read in the threshold, loadfactor, and any hidden stuff
737         s.defaultReadObject();
738 
739         // 先读数组的长度
740         int numBuckets = s.readInt();
741         table = new Entry[numBuckets];
742 
743         init();  //调用初始化函数
744         // 先读元素的个数
745         int size = s.readInt();
746 
747         //  然后再把一个一个的元素读出到输入流对象中
748         for (int i=0; i<size; i++) {
749             K key = (K) s.readObject();
750             V value = (V) s.readObject();
751             putForCreate(key, value);
752         }
753     }
754 
755     // 返回“HashMap总的容量”
756     int   capacity()     { return table.length; }
757     // 返回“HashMap的加载因子”
758     float loadFactor()   { return loadFactor;   }
759 }
View Code

3.1、HashMap的“拉链法”相关内容

transient Entry[] table;

HashMap中的key-value都是存储在Entry数组中的。

 1 static class Entry<K,V> implements Map.Entry<K,V> {
 2     final K key;
 3     V value;
 4     // 指向下一个节点
 5     Entry<K,V> next;
 6     final int hash;
 7 
 8     // 构造函数。
 9     // 输入参数包括"哈希值(h)", "键(k)", "值(v)", "下一节点(n)"
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     // 判断两个Entry是否相等
32     // 若两个Entry的“key”和“value”都相等,则返回true。
33     // 否则,返回false
34     public final boolean equals(Object o) {
35         if (!(o instanceof Map.Entry))
36             return false;
37         Map.Entry e = (Map.Entry)o;
38         Object k1 = getKey();
39         Object k2 = e.getKey();
40         if (k1 == k2 || (k1 != null && k1.equals(k2))) {
41             Object v1 = getValue();
42             Object v2 = e.getValue();
43             if (v1 == v2 || (v1 != null && v1.equals(v2)))
44                 return true;
45         }
46         return false;
47     }
48 
49     // 实现hashCode()
50     public final int hashCode() {
51         return (key==null   ? 0 : key.hashCode()) ^
52                (value==null ? 0 : value.hashCode());
53     }
54 
55     public final String toString() {
56         return getKey() + "=" + getValue();
57     }
58 
59     // 当向HashMap中添加元素时,绘调用recordAccess()。
60     // 这里不做任何处理
61     void recordAccess(HashMap<K,V> m) {
62     }
63 
64     // 当从HashMap中删除元素时,绘调用recordRemoval()。
65     // 这里不做任何处理
66     void recordRemoval(HashMap<K,V> m) {
67     }
68 }
数据节点Entry的数据结构

从源代码中我们可以看出 Entry实际上就是一个单向链表。这也是为什么我们说HashMap是通过拉链法解决哈希冲突的。
Entry 实现了Map.Entry 接口,即实现getKey(), getValue(), setValue(V value), equals(Object o), hashCode()这些函数。这些都是基本的读取/修改key、value值的函数。

3.2、HashMap的构造函数

 1 // 默认构造函数。
 2 public HashMap() {
 3     // 设置“加载因子”
 4     this.loadFactor = DEFAULT_LOAD_FACTOR;
 5     // 设置“HashMap阈值”,当HashMap中存储数据的数量达到threshold时,就需要将HashMap的容量加倍。
 6     threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
 7     // 创建Entry数组,用来保存数据
 8     table = new Entry[DEFAULT_INITIAL_CAPACITY];
 9     init();
10 }
11 
12 // 指定“容量大小”和“加载因子”的构造函数
13 public HashMap(int initialCapacity, float loadFactor) {
14     if (initialCapacity < 0)
15         throw new IllegalArgumentException("Illegal initial capacity: " +
16                                            initialCapacity);
17     // HashMap的最大容量只能是MAXIMUM_CAPACITY
18     if (initialCapacity > MAXIMUM_CAPACITY)
19         initialCapacity = MAXIMUM_CAPACITY;
20     if (loadFactor <= 0 || Float.isNaN(loadFactor))
21         throw new IllegalArgumentException("Illegal load factor: " +
22                                            loadFactor);
23 
24     // Find a power of 2 >= initialCapacity
25     int capacity = 1;
26     while (capacity < initialCapacity)
27         capacity <<= 1;
28 
29     // 设置“加载因子”
30     this.loadFactor = loadFactor;
31     // 设置“HashMap阈值”,当HashMap中存储数据的数量达到threshold时,就需要将HashMap的容量加倍。
32     threshold = (int)(capacity * loadFactor);
33     // 创建Entry数组,用来保存数据
34     table = new Entry[capacity];
35     init();
36 }
37 
38 // 指定“容量大小”的构造函数
39 public HashMap(int initialCapacity) {
40     this(initialCapacity, DEFAULT_LOAD_FACTOR);
41 }
42 
43 // 包含“子Map”的构造函数
44 public HashMap(Map<? extends K, ? extends V> m) {
45     this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
46                   DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
47     // 将m中的全部元素逐个添加到HashMap中
48     putAllForCreate(m);
49 }
hashMap的四种构造函数

3.3、HashMap的主要对外接口

  • clear():clear() 的作用是清空HashMap。它是通过将所有的元素设为null来实现的。
    1 public void clear() {
    2     modCount++;
    3     Entry[] tab = table;
    4     for (int i = 0; i < tab.length; i++)
    5         tab[i] = null;
    6     size = 0;
    7 }
    clear()源代码
  • containsKey():containsKey()的作用是判断HashMap是否包含key
    public boolean containsKey(Object key) {
        return getEntry(key) != null; }

    containsKey() 首先通过getEntry(key)获取key对应的Entry,然后判断该Entry是否为nullgetEntry() 的作用就是返回“键为key”的键值对,它的实现源码中已经进行了说明。这里需要强调的是:HashMap将“key为null”的元素都放在table的位置0处,即table[0]中;“key不为null”的放在table的其余位置!
    getEntry()的源码如下:

     1 final Entry<K,V> getEntry(Object key) {
     2     // 获取哈希值
     3     // HashMap将“key为null”的元素存储在table[0]位置,“key不为null”的则调用hash()计算哈希值
     4     int hash = (key == null) ? 0 : hash(key.hashCode());
     5     // 在“该hash值对应的链表”上查找“键值等于key”的元素
     6     for (Entry<K,V> e = table[indexFor(hash, table.length)];
     7          e != null;
     8          e = e.next) {
     9         Object k;
    10         if (e.hash == hash &&
    11             ((k = e.key) == key || (key != null && key.equals(k))))
    12             return e;
    13     }
    14     return null;
    15 }
    View Code
  • containsValue():containsValue()的作用是判断HashMap是否包含“值为value”的元素

    从中,我们可以看出containsNullValue()分为两步进行处理:第一,若“value为null”,则调用containsNullValue()。第二,若“value不为null”,则查找HashMap中是否有值为value的节点。

     1 public boolean containsValue(Object value) {
     2     // 若“value为null”,则调用containsNullValue()查找
     3     if (value == null)
     4         return containsNullValue();
     5 
     6     // 若“value不为null”,则查找HashMap中是否有值为value的节点。
     7     Entry[] tab = table;
     8     for (int i = 0; i < tab.length ; i++)
     9         for (Entry e = tab[i] ; e != null ; e = e.next)
    10             if (value.equals(e.value))
    11                 return true;
    12     return false;
    13 }
    View Code

    containsNullValue() 的作用判断HashMap中是否包含“值为null”的元素

    1 private boolean containsNullValue() {
    2     Entry[] tab = table;
    3     for (int i = 0; i < tab.length ; i++)
    4         for (Entry e = tab[i] ; e != null ; e = e.next)
    5             if (e.value == null)
    6                 return true;
    7     return false;
    8 }
    View Code
  • entrySet()、values()、keySet():它们3个的原理类似,这里以entrySet()为例来说明。entrySet()的作用是返回“HashMap中所有Entry的集合”,它是一个集合。实现代码如下:
     1 // 返回“HashMap的Entry集合”
     2 public Set<Map.Entry<K,V>> entrySet() {
     3     return entrySet0();
     4 }
     5 
     6 // 返回“HashMap的Entry集合”,它实际是返回一个EntrySet对象
     7 private Set<Map.Entry<K,V>> entrySet0() {
     8     Set<Map.Entry<K,V>> es = entrySet;
     9     return es != null ? es : (entrySet = new EntrySet());
    10 }
    11 
    12 // EntrySet对应的集合
    13 // EntrySet继承于AbstractSet,说明该集合中没有重复的EntrySet。
    14 private final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
    15     public Iterator<Map.Entry<K,V>> iterator() {
    16         return newEntryIterator();
    17     }
    18     public boolean contains(Object o) {
    19         if (!(o instanceof Map.Entry))
    20             return false;
    21         Map.Entry<K,V> e = (Map.Entry<K,V>) o;
    22         Entry<K,V> candidate = getEntry(e.getKey());
    23         return candidate != null && candidate.equals(e);
    24     }
    25     public boolean remove(Object o) {
    26         return removeMapping(o) != null;
    27     }
    28     public int size() {
    29         return size;
    30     }
    31     public void clear() {
    32         HashMap.this.clear();
    33     }
    34 }
    View Code

    HashMap是通过拉链法实现的散列表。表现在HashMap包括许多的Entry,而每一个Entry本质上又是一个单向链表。那么HashMap遍历key-value键值对的时候,是如何逐个去遍历的呢?

    下面我们就看看HashMap是如何通过entrySet()遍历的。
    entrySet()实际上是通过newEntryIterator()实现的。 下面我们看看它的代码:

     1 // 返回一个“entry迭代器”
     2 Iterator<Map.Entry<K,V>> newEntryIterator()   {
     3     return new EntryIterator();
     4 }
     5 
     6 // Entry的迭代器
     7 private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
     8     public Map.Entry<K,V> next() {
     9         return nextEntry();
    10     }
    11 }
    12 
    13 // HashIterator是HashMap迭代器的抽象出来的父类,实现了公共了函数。
    14 // 它包含“key迭代器(KeyIterator)”、“Value迭代器(ValueIterator)”和“Entry迭代器(EntryIterator)”3个子类。
    15 private abstract class HashIterator<E> implements Iterator<E> {
    16     // 下一个元素
    17     Entry<K,V> next;
    18     // expectedModCount用于实现fast-fail机制。
    19     int expectedModCount;
    20     // 当前索引
    21     int index;
    22     // 当前元素
    23     Entry<K,V> current;
    24 
    25     HashIterator() {
    26         expectedModCount = modCount;
    27         if (size > 0) { // advance to first entry
    28             Entry[] t = table;
    29             // 将next指向table中第一个不为null的元素。
    30             // 这里利用了index的初始值为0,从0开始依次向后遍历,直到找到不为null的元素就退出循环。
    31             while (index < t.length && (next = t[index++]) == null)
    32                 ;
    33         }
    34     }
    35 
    36     public final boolean hasNext() {
    37         return next != null;
    38     }
    39 
    40     // 获取下一个元素
    41     final Entry<K,V> nextEntry() {
    42         if (modCount != expectedModCount)
    43             throw new ConcurrentModificationException();
    44         Entry<K,V> e = next;
    45         if (e == null)
    46             throw new NoSuchElementException();
    47 
    48         // 注意!!!
    49         // 一个Entry就是一个单向链表
    50         // 若该Entry的下一个节点不为空,就将next指向下一个节点;
    51         // 否则,将next指向下一个链表(也是下一个Entry)的不为null的节点。
    52         if ((next = e.next) == null) {
    53             Entry[] t = table;
    54             while (index < t.length && (next = t[index++]) == null)
    55                 ;
    56         }
    57         current = e;
    58         return e;
    59     }
    60 
    61     // 删除当前元素
    62     public void remove() {
    63         if (current == null)
    64             throw new IllegalStateException();
    65         if (modCount != expectedModCount)
    66             throw new ConcurrentModificationException();
    67         Object k = current.key;
    68         current = null;
    69         HashMap.this.removeEntryForKey(k);
    70         expectedModCount = modCount;
    71     }
    72 
    73 }
    View Code

    当我们通过entrySet()获取到的Iterator的next()方法去遍历HashMap时,实际上调用的是 nextEntry() 。而nextEntry()的实现方式,先遍历Entry(根据Entry在table中的序号,从小到大的遍历);然后对每个Entry(即每个单向链表),逐个遍历。

  • put():put() 的作用是对外提供接口,让HashMap对象可以通过put()将“key-value”添加到HashMap中
     1 public V put(K key, V value) {
     2     // 若“key为null”,则将该键值对添加到table[0]中。
     3     if (key == null)
     4         return putForNullKey(value);
     5     // 若“key不为null”,则计算该key的哈希值,然后将其添加到该哈希值对应的链表中。
     6     int hash = hash(key.hashCode());
     7     int i = indexFor(hash, table.length);
     8     for (Entry<K,V> e = table[i]; e != null; e = e.next) {
     9         Object k;
    10         // 若“该key”对应的键值对已经存在,则用新的value取代旧的value。然后退出!
    11         if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
    12             V oldValue = e.value;
    13             e.value = value;
    14             e.recordAccess(this);
    15             return oldValue;
    16         }
    17     }
    18 
    19     // 若“该key”对应的键值对不存在,则将“key-value”添加到table中
    20     modCount++;
    21     addEntry(hash, key, value, i);
    22     return null;
    23 }
    View Code

    若要添加到HashMap中的键值对对应的key已经存在HashMap中,则找到该键值对;然后新的value取代旧的value,并退出!
    若要添加到HashMap中的键值对对应的key不在HashMap中,则将其添加到该哈希值对应的链表中,并调用addEntry()。
    下面看看addEntry()的代码:

     1 void addEntry(int hash, K key, V value, int bucketIndex) {
     2     // 保存“bucketIndex”位置的值到“e”中
     3     Entry<K,V> e = table[bucketIndex];
     4     // 设置“bucketIndex”位置的元素为“新Entry”,
     5     // 设置“e”为“新Entry的下一个节点”
     6     table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
     7     // 若HashMap的实际大小 不小于 “阈值”,则调整HashMap的大小
     8     if (size++ >= threshold)
     9         resize(2 * table.length);
    10 }
    View Code

    addEntry() 的作用是新增Entry。将“key-value”插入指定位置,bucketIndex是位置索引。

    说到addEntry(),就不得不说另一个函数createEntry()。createEntry()的代码如下:

    1 void createEntry(int hash, K key, V value, int bucketIndex) {
    2     // 保存“bucketIndex”位置的值到“e”中
    3     Entry<K,V> e = table[bucketIndex];
    4     // 设置“bucketIndex”位置的元素为“新Entry”,
    5     // 设置“e”为“新Entry的下一个节点”
    6     table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
    7     size++;
    8 }
    View Code

    它们的作用都是将key、value添加到HashMap中。而且,比较addEntry()和createEntry()的代码,我们发现addEntry()多了两句:

    if (size++ >= threshold)
        resize(2 * table.length);

    那它们的区别到底是什么呢?
    通过阅读源代码,我们可以发现,它们的使用情景不同。
    (01) addEntry()一般用在 新增Entry可能导致“HashMap的实际容量”超过“阈值”的情况下。
         例如,我们新建一个HashMap,然后不断通过put()向HashMap中添加元素;put()是通过addEntry()新增Entry的。
         在这种情况下,我们不知道何时“HashMap的实际容量”会超过“阈值”;因此,需要调用addEntry()
    (02) createEntry() 一般用在 新增Entry不会导致“HashMap的实际容量”超过“阈值”的情况下。
        例如,我们调用HashMap“带有Map”的构造函数,它绘将Map的全部元素添加到HashMap中;
        但在添加之前,我们已经计算好“HashMap的容量和阈值”。也就是,可以确定“即使将Map中的全部元素添加到HashMap中,都不会超过HashMap的阈值”。此时,调用createEntry()即可。

3.4、HashMap实现的Cloneable接口

HashMap实现了Cloneable接口,即实现了clone()方法。
clone()方法的作用很简单,就是克隆一个HashMap对象并返回。

 1 // 克隆一个HashMap,并返回Object对象
 2 public Object clone() {
 3     HashMap<K,V> result = null;
 4     try {
 5         result = (HashMap<K,V>)super.clone();
 6     } catch (CloneNotSupportedException e) {
 7         // assert false;
 8     }
 9     result.table = new Entry[table.length];
10     result.entrySet = null;
11     result.modCount = 0;
12     result.size = 0;
13     result.init();
14     // 调用putAllForCreate()将全部元素添加到HashMap中
15     result.putAllForCreate(this);
16 
17     return result;
18 }
View Code

3.5、HashMap实现的Serializable接口

HashMap实现java.io.Serializable,分别实现了串行读取、写入功能。
串行写入函数是writeObject(),它的作用是将HashMap的“总的容量,实际容量,所有的Entry”都写入到输出流中。
而串行读取函数是readObject(),它的作用是将HashMap的“总的容量,实际容量,所有的Entry”依次读出

 1  // java.io.Serializable的写入函数
 2     // 将HashMap的“总的容量,实际容量,所有的Entry”都写入到输出流中
 3     private void writeObject(java.io.ObjectOutputStream s)
 4         throws IOException
 5     {
 6         Iterator<Map.Entry<K,V>> i =
 7             (size > 0) ? entrySet0().iterator() : null;
 8         // Write out the threshold, loadfactor, and any hidden stuff
 9         s.defaultWriteObject();
10        //先写数组的长度
11         s.writeInt(table.length);
12         // 再写数据元素的大小
13         s.writeInt(size);
14         // 然后再把一个一个的元素写进输出流对象中
15         if (i != null) {
16             while (i.hasNext()) {
17             Map.Entry<K,V> e = i.next();
18             s.writeObject(e.getKey());
19             s.writeObject(e.getValue());
20             }
21         }
22     }
23     private static final long serialVersionUID = 362498820763181265L;
24     // java.io.Serializable的读取函数:根据写入方式读出
25     // 将HashMap的“总的容量,实际容量,所有的Entry”依次读出
26     private void readObject(java.io.ObjectInputStream s)
27          throws IOException, ClassNotFoundException
28     {
29         // Read in the threshold, loadfactor, and any hidden stuff
30         s.defaultReadObject();
31 
32         // 先读数组的长度
33         int numBuckets = s.readInt();
34         table = new Entry[numBuckets];
35 
36         init();  //调用初始化函数
37         // 先读元素的个数
38         int size = s.readInt();
39 
40         //  然后再把一个一个的元素读出到输入流对象中
41         for (int i=0; i<size; i++) {
42             K key = (K) s.readObject();
43             V value = (V) s.readObject();
44             putForCreate(key, value);
45         }
46     }
View Code

4、HashMap遍历方式

4.1、遍历HashMap的键值对

 1 // 假设map是HashMap对象
 2 // map中的key是String类型,value是Integer类型
 3 Integer integ = null;
 4 Iterator iter = map.entrySet().iterator();
 5 while(iter.hasNext()) {
 6     Map.Entry entry = (Map.Entry)iter.next();
 7     // 获取key
 8     key = (String)entry.getKey();
 9         // 获取value
10     integ = (Integer)entry.getValue();
11 }

4.2、遍历HashMap的键

 1 // 假设map是HashMap对象
 2 // map中的key是String类型,value是Integer类型
 3 String key = null;
 4 Integer integ = null;
 5 Iterator iter = map.keySet().iterator();
 6 while (iter.hasNext()) {
 7         // 获取key
 8     key = (String)iter.next();
 9         // 根据key,获取value
10     integ = (Integer)map.get(key);
11 }

4.3、遍历HashMap的值

1 // 假设map是HashMap对象
2 // map中的key是String类型,value是Integer类型
3 Integer value = null;
4 Collection c = map.values();
5 Iterator iter= c.iterator();
6 while (iter.hasNext()) {
7     value = (Integer)iter.next();
8 }

5、HashMap测试实例

 1 import java.util.Map;
 2 import java.util.Random;
 3 import java.util.Iterator;
 4 import java.util.HashMap;
 5 import java.util.HashSet;
 6 import java.util.Map.Entry;
 7 import java.util.Collection;
 8 
 9 /*
10  *  HashMap测试程序
11  *        
12  */
13 public class HashMapTest {
14 
15     public static void main(String[] args) {
16         testHashMapAPIs();
17     }
18     
19     private static void testHashMapAPIs() {
20         // 初始化随机种子
21         Random r = new Random();
22         // 新建HashMap
23         HashMap map = new HashMap();
24         // 添加操作
25         map.put("one", r.nextInt(10));
26         map.put("two", r.nextInt(10));
27         map.put("three", r.nextInt(10));
28 
29         // 打印出map
30         System.out.println("map:"+map );
31 
32         // 通过Iterator遍历key-value
33         Iterator iter = map.entrySet().iterator();
34         while(iter.hasNext()) {
35             Map.Entry entry = (Map.Entry)iter.next();
36             System.out.println("next : "+ entry.getKey() +" - "+entry.getValue());
37         }
38 
39         // HashMap的键值对个数        
40         System.out.println("size:"+map.size());
41 
42         // containsKey(Object key) :是否包含键key
43         System.out.println("contains key two : "+map.containsKey("two"));
44         System.out.println("contains key five : "+map.containsKey("five"));
45 
46         // containsValue(Object value) :是否包含值value
47         System.out.println("contains value 0 : "+map.containsValue(new Integer(0)));
48 
49         // remove(Object key) : 删除键key对应的键值对
50         map.remove("three");
51 
52         System.out.println("map:"+map );
53 
54         // clear() : 清空HashMap
55         map.clear();
56 
57         // isEmpty() : HashMap是否为空
58         System.out.println((map.isEmpty()?"map is empty":"map is not empty") );
59     }
60 }
View Code

测试程序运行结果:

 1 map:{two=7, one=9, three=6}
 2 next : two - 7
 3 next : one - 9
 4 next : three - 6
 5 size:3
 6 contains key two : true
 7 contains key five : false
 8 contains value 0 : false
 9 map:{two=7, one=9}
10 map is empty

猜你喜欢

转载自www.cnblogs.com/BaoZiY/p/10663030.html