Java HashMap的資料結構以及put和get方法__arcinfo

來源:互聯網
上載者:User

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.