HashMap解惑
HashMap中有一些我們容易忽視的點,
Java代碼??
public?V?put(K?key,?V?value)?{??
????????if?(table?==?EMPTY_TABLE)?{??
????????????inflateTable(threshold);??
????????}??
????????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;??
????}??
?由上述代碼知道,hash值是用來確定bucketIndex,equals是用來和鏈表上的值比較,因此對于key是自定義的類,強烈建議重寫hashCode和equals方法。
?再看如下代碼下載
Java代碼??
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);??
????}??
?if條件告訴我們rehash的條件要同時滿足兩個:map中元素個數不小于閥值即容量*負載因子,對應的bucketIndex處有元素。
?另外,如下代碼作備忘,
Java代碼??
static?int?indexFor(int?h,?int?length)?{??
????????//?assert?Integer.bitCount(length)?==?1?:?"length?must?be?a?non-zero?power?of?2";??
????????return?h?&?(length-1);??
????} ?
轉載于:https://blog.51cto.com/11696680/1867927
總結
- 上一篇: Android性能优化工具
- 下一篇: 35 mysql 备份与恢复