标签:
HashTable:
1 /** 2 * Hashtable collision list. 3 */ 4 private static class Entry<K,V> implements Map.Entry<K,V> { 5 int hash; 6 K key; 7 V value; 8 Entry<K,V> next; 9 10 protected Entry(int hash, K key, V value, Entry<K,V> next) { 11 this.hash = hash; 12 this.key = key; 13 this.value = value; 14 this.next = next; 15 } 16 17 protected Object clone() { 18 return new Entry<K,V>(hash, key, value, 19 (next==null ? null : (Entry<K,V>) next.clone())); 20 } 21 22 // Map.Entry Ops 23 24 public K getKey() { 25 return key; 26 } 27 28 public V getValue() { 29 return value; 30 } 31 32 public V setValue(V value) { 33 if (value == null) 34 throw new NullPointerException(); 35 36 V oldValue = this.value; 37 this.value = value; 38 return oldValue; 39 } 40 41 public boolean equals(Object o) { 42 if (!(o instanceof Map.Entry)) 43 return false; 44 Map.Entry e = (Map.Entry)o; 45 46 return (key==null ? e.getKey()==null : key.equals(e.getKey())) && 47 (value==null ? e.getValue()==null : value.equals(e.getValue())); 48 } 49 50 public int hashCode() { 51 return hash ^ (value==null ? 0 : value.hashCode()); 52 } 53 54 public String toString() { 55 return key.toString()+"="+value.toString(); 56 } 57 }
HashMap:
1 /** 2 * Applies a supplemental hash function to a given hashCode, which 3 * defends against poor quality hash functions. This is critical 4 * because HashMap uses power-of-two length hash tables, that 5 * otherwise encounter collisions for hashCodes that do not differ 6 * in lower bits. Note: Null keys always map to hash 0, thus index 0. 7 */ 8 static int hash(int h) { 9 // This function ensures that hashCodes that differ only by 10 // constant multiples at each bit position have a bounded 11 // number of collisions (approximately 8 at default load factor). 12 h ^= (h >>> 20) ^ (h >>> 12); 13 return h ^ (h >>> 7) ^ (h >>> 4); 14 }
然后处理hash值,其中h = hash(key.hashCode()), length = table.length();
1 /** 2 * Returns index for hash code h. 3 */ 4 static int indexFor(int h, int length) { 5 return h & (length-1); 6 }
标签:
原文地址:http://www.cnblogs.com/ibuki/p/4832391.html