還是調試源碼最好。
開發環境 JDK1.8+NetBeans8.1
說明:調試HashMap的 public V put(K key, V value) 方法並查看key的值時不能顯示變量的值,原因在於oracle提供的jre中rt.jar不帶debug信息。
orcale在編譯src時使用了 javac -g:none,意思是不帶任何調試信息,這樣可以減小rt.jar的大小。若想正常調試jdk,就只能重新編譯src.zip。
當然也可以只編譯單個需要關注的Java即可,例如HashMap.java。
一.解壓src.zip
解壓src.zip到E:\workspace\下,
src.zip在安裝的C:\Program Files\Java\jdk1.8.0_25下
二.javac -g重編譯
重新編譯src\java\util下的HashMap.java
Windows下進入DOS環境,輸入
E:\workspace\src\java\util
然後再輸入E:就直接到了E:\workspace\src\java\util
默認如果不帶-g編譯是沒有調試信息是不夠的。
# javac -g HashMap.java
三.替換rt.jar
將編譯好的所有的HashMap.class都放入C:\Program Files\Java\jdk1.8.0_25\jre\lib的rt.jar
說明:需要做好備份以防搞錯。
四.調試HashMap
先看看HashMap的理論吧
- import java.util.HashMap;
- import java.util.Map;
- import org.junit.Test;
- public class TestHash {
- @Test
- public void testHashMap() throws Exception {
- System.out.println("==========================");
- Map<String, String> m = new HashMap<String, String>();
- for (int i = 0; i < 18; i++) {
- m.put((char) (i + 65) + (char) (i + 66) + (char) (i + 67) + "", i + ">>>http://blog.csdn.net/unix21/");
- }
- System.out.println("==========================");
- }
- }
下面是源碼
- /**
- * 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) {
- return putVal(hash(key), key, value, false, true);
- }
- /**
- * Implements Map.put and related methods
- *
- * @param hash hash for key
- * @param key the key
- * @param value the value to put
- * @param onlyIfAbsent if true, don't change existing value
- * @param evict if false, the table is in creation mode.
- * @return previous value, or null if none
- */
- 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;
- }
1.第一次進入源碼
先初始化增長因子
一開始聲明一個
- transient Node<K,V>[] table;
java 的transient關鍵字爲我們提供了便利,你只需要實現Serilizable接口,將不需要序列化的屬性前添加關鍵字transient,序列化對象的時候,這個屬性就不會序列化到指定的目的地中。
函數體內聲明一個Node<K,V>[] tab
一開始table=null,所以tab也是null的
可以看到n=16,如果不使用-g編譯是看不到n的,這說明初始的tab長度是16。
然後給tab進行初始化,p=tab[0]=null
2.插入newNode
最終會調用static class Node<K,V>的Node(int hash, K key, V value, Node<K,V> next)
- /**
- * Basic hash bin node, used for most entries. (See below for
- * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
- */
- static class Node<K,V> implements Map.Entry<K,V> {
- final int hash;
- final K key;
- V value;
- Node<K,V> next;
- Node(int hash, K key, V value, Node<K,V> next) {
- this.hash = hash;
- this.key = key;
- this.value = value;
- this.next = next;
- }
- public final K getKey() { return key; }
- public final V getValue() { return value; }
- public final String toString() { return key + "=" + value; }
- public final int hashCode() {
- return Objects.hashCode(key) ^ Objects.hashCode(value);
- }
- public final V setValue(V newValue) {
- V oldValue = value;
- value = newValue;
- return oldValue;
- }
- public final boolean equals(Object o) {
- if (o == this)
- return true;
- if (o instanceof Map.Entry) {
- Map.Entry<?,?> e = (Map.Entry<?,?>)o;
- if (Objects.equals(key, e.getKey()) &&
- Objects.equals(value, e.getValue()))
- return true;
- }
- return false;
- }
- }
第一個Node節點就有值了,其next爲null.
關於靜態嵌套類
3.回到putVal
tab[0]就是返回的Node
4.查看是否需要擴容
還不到threshold的上限12 ,所以無需擴容。
5.HashMap第二次put進入putVal
很顯然這個時候table不爲空,因爲前次已經插值了。
i=3,p=tab[3]
新的node插入在tab[3]上,此次依然無需擴容。
第4次插值
第7次插值
第11次
第12次
第13次
tab和
此次需要擴容
點開oldTab
下一步
下一步
下一步,threshold升爲24
下一步
newTab
oldTab
oldTab[0]
oldTab[j] = null;
下一步
下一步next = e.next;
下一步
下一步
下一步
下一步(e = next) != null
下一步
經過N此循環之後
newTab
oldTab
回到putVal
擴容之後再次進入第14次進入
tab
關於HashMap就分析到此,網上有幾篇寫的不錯的帖子結合看看就更明白了,建議閱讀下:
深入Java集合學習系列:HashMap的實現原理 引文 深入Java集合學習系列:HashMap的實現原理 原文
HashMap什麼時候進行擴容呢?當HashMap中的元素個數超過數組大小*loadFactor時,就會進行數組擴容,loadFactor的默認值爲0.75,這是一個折中的取值。
也就是說,默認情況下,數組大小爲16,那麼當HashMap中元素個數超過16*0.75=12(這個值就是代碼中的threshold值,也叫做臨界值)的時候,就把數組的大小擴展爲 2*16=32,即擴大一倍,
然後重新計算每個元素在數組中的位置,而這是一個非常消耗性能的操作,所以如果我們已經預知HashMap中元素的個數,那麼預設元素的個數能夠有效的提高HashMap的性能。
注:本文轉自http://blog.csdn.net/unix21/article/details/50911387