国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

JDK源碼之解讀hashMap 的put和get方法的實現原理

2019-11-09 20:20:02
字體:
來源:轉載
供稿:網友
JDK源碼之解讀hashMap 的put和get方法的實現原理1,put             對于方法hashmap.put(K,V),首先是把k處理,通過hashcode方法處理得到K對應的hash=hash(K).             再調用h & (length-1)得到數組下標i. 最后調用createEntry(hash, key, value, i)方法,把hash,key,value存入table[i]一維數組中。源碼如下:             
 public V put(K key, V value) {        if (key == null)            return putForNullKey(value);        int hash = hash(key);        int i = indexFor(hash, table.length);        for (Entry<K,V> e = table[i]; e != null; e = e.next) {            Object k;            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {                V oldValue = e.value;                e.value = value;                e.recordaccess(this);                return oldValue;            }        }        modCount++;        addEntry(hash, key, value, i);        return null;    }
 final int hash(Object k) {        int h = 0;        if (useAltHashing) {            if (k instanceof String) {                return sun.misc.Hashing.stringHash32((String) k);            }            h = hashSeed;        }        h ^= k.hashCode();        // This function ensures that hashCodes that differ only by        // constant multiples at each bit position have a bounded        // number of collisions (apPRoximately 8 at default load factor).        h ^= (h >>> 20) ^ (h >>> 12);        return h ^ (h >>> 7) ^ (h >>> 4);    }
 void addEntry(int hash, K key, V value, int bucketIndex) {        if ((size >= threshold) && (null != table[bucketIndex])) {            resize(2 * table.length);            hash = (null != key) ? hash(key) : 0;            bucketIndex = indexFor(hash, table.length);        }        createEntry(hash, key, value, bucketIndex);    }
總結就是說,先用鍵生成hashcode,然后把鍵和值存入一個對象為鍵值對的一維數組中,位置是,按生成hashcode轉變得到的數字作為一維數組的下標。
有人會說,萬一生成的hashcode一樣咋辦?=== 因為他是把鍵值對存入一維數組中,鍵是唯一的,所以hashcode一樣時候,根據對象里面的鍵不同,一樣可以取出唯一對應的值。
2,get           弄懂put方法原理,這個就很簡單了。根據對應的鍵,找到hashcode,去一維數組根據hashcode生成的下標去取對應的值,           如果hashcode一樣,根據唯一鍵在一位數組里面取值。源碼如下:          
  public V get(Object key) {        if (key == null)            return getForNullKey();        Entry<K,V> entry = getEntry(key);        return null == entry ? null : entry.getValue();    }
  final Entry<K,V> getEntry(Object key) {        int hash = (key == null) ? 0 : hash(key);        for (Entry<K,V> e = table[indexFor(hash, table.length)];             e != null;             e = e.next) {            Object k;            if (e.hash == hash &&                ((k = e.key) == key || (key != null && key.equals(k))))                return e;        }        return null;    }
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 葵青区| 包头市| 东乡| 贞丰县| 玉龙| 威海市| 七台河市| 山丹县| 闸北区| 涡阳县| 婺源县| 宁阳县| 开原市| 西丰县| 县级市| 黎川县| 大安市| 弥渡县| 河南省| 五河县| 鄄城县| 娄底市| 黔东| 宁河县| 德州市| 临湘市| 漳州市| 江都市| 和林格尔县| 赤水市| 锦州市| 文水县| 苏尼特左旗| 慈利县| 永宁县| 和政县| 达尔| 屏边| 三亚市| 望奎县| 香港 |