HashMap源碼淺析
阿新 • • 發佈:2018-03-11
OS hash沖突 efault map.entry AD ash spa span tostring
HashMap源碼主要一些屬性
//默認的初始化容量(2的n次方)
static final int default_inital_capacity = 16;
//最大指定容量為2的30次方
static final int maximum_capacity = 1 << 30;
//默認的加載因子
static final float default_load_factor = 0.75f;
//hashmap的底層結構,entry數組
transient Entry[] table;
//存放的key-value對的個數,決定了數組的擴容,默認16 * 0.75 = 12,當size > 12時,就擴容,而非table中
所占用的桶(table[i])個數來決定是否擴容
transient int size;
Entry內部類
1 static class Entry<K, V> implements Map.Entry<K, V> { 2 final K key; 3 V value; 4 Entry<K, V> next; // 該Entry的下一個Entry(hash沖突時,形成鏈表) 5 final int hash; // 該Entry的hash值6 7 /** 8 * Creates new entry. 9 */ 10 Entry(int h, K k, V v, Entry<K, V> n) { 11 value = v; 12 next = n; 13 key = k; 14 hash = h; 15 } 16 17 public final K getKey() { 18 return key;19 } 20 21 public final V getValue() { 22 return value; 23 } 24 25 //為Entry設置新的value 26 public final V setValue(V newValue) { 27 V oldValue = value; 28 value = newValue; 29 return oldValue; 30 } 31 32 public final boolean equals(Object o) { 33 if (!(o instanceof Map.Entry)) 34 return false; 35 Map.Entry e = (Map.Entry) o; 36 Object k1 = getKey(); 37 Object k2 = e.getKey(); 38 //在hashmap中可以存放null鍵和null值 39 if (k1 == k2 || (k1 != null && k1.equals(k2))) { 40 Object v1 = getValue(); 41 Object v2 = e.getValue(); 42 if (v1 == v2 || (v1 != null && v1.equals(v2))) 43 return true; 44 } 45 return false; 46 } 47 48 public final int hashCode() { 49 return (key == null ? 0 : key.hashCode())^(value == null ? 0 : value.hashCode()); 50 } 51 52 public final String toString() { 53 return getKey() + "=" + getValue(); 54 } 55 }
HashMap源碼淺析