1 HashMap的資料結構
HashMap實際上是一個鏈表數組,也就是最外層是數組,數組的元素是鏈表。
2 HashMap的put方法:
原始碼如下:
<span style="font-size:10px;"> public V put(K key, V value) { //1 如果Key為Null 則put到Key為null的位置 if (key == null) return putForNullKey(value); //2 計算Key的hash值 int hash = hash(key.hashCode()); //3 擷取index位置 int i = indexFor(hash, table.length); //4 遍曆index位置的鏈表,如果存在則覆蓋並返回舊值,如果不存在就建立一個新位置插入 for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; //4.1 Key的位置已經有舊的值了 則把新值給舊值 並返回舊值 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } //4.2 如果Key是新的則調用addEntry插入新的Key和value modCount++; addEntry(hash, key, value, i); return null; }</span>
3 原始碼如下HashMap的get方法:
原始碼如下:
<span style="font-size:10px;"> public V get(Object key) { //1 如果Key是null 直接返回key為null位置的值 if (key == null) return getForNullKey(); //2 計算Key對象的hash值 int hash = hash(key.hashCode()); for (Entry<K,V> e = table[indexFor(hash, table.length)]; //通過計算Key的hash找到index e != null; e = e.next) {//在index中找遍曆鏈表 Object k; //通過equals比較找到Key位置 如果找到Key 並返回value if (e.hash == hash && ((k = e.key) == key || key.equals(k))) return e.value; } return null; }</span>
4 concurrentHashMap的分析:
主要是劃分segment
參考資料:
java提高篇(二三)-----HashMap
源碼分析之ConcurrentHashMap