看了下JAVA裏面有HashMap、Hashtable、HashSet三種hash集合的實現源碼,這裏總結下,理解錯誤的地方還望指正 html
HashSet和HashMap、Hashtable的區別 安全
int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length;
HashMap計算hash對key的hashcode進行了二次hash,以得到更好的散列值,而後對table數組長度取摸 ide
static int hash(int h) { // 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); } static int indexFor(int h, int length) { return h & (length-1); }
除開HashMap和Hashtable外,還有一個hash集合HashSet,有所區別的是HashSet不是key value結構,僅僅是存儲不重複的元素,至關於簡化版的HashMap,只是包含HashMap中的key而已 性能
經過查看源碼也證明了這一點,HashSet內部就是使用HashMap實現,只不過HashSet裏面的HashMap全部的value都是同一個Object而已,所以HashSet也是非線程安全的,至於HashSet和Hashtable的區別,HashSet就是個簡化的HashMap的,因此你懂的
下面是HashSet幾個主要方法的實現 ui
private transient HashMap<E,Object> map; private static final Object PRESENT = new Object(); public HashSet() { map = new HashMap<E,Object>(); } public boolean contains(Object o) { return map.containsKey(o); } public boolean add(E e) { return map.put(e, PRESENT)==null; } public boolean add(E e) { return map.put(e, PRESENT)==null; } public boolean remove(Object o) { return map.remove(o)==PRESENT; } public void clear() { map.clear(); }
HashMap和Hashtable的底層實現都是數組+鏈表結構實現的,這點上徹底一致 this
添加、刪除、獲取元素時都是先計算hash,根據hash和table.length計算index也就是table數組的下標,而後進行相應操做,下面以HashMap爲例說明下它的簡單實現 spa
/** * HashMap的默認初始容量 必須爲2的n次冪 */ static final int DEFAULT_INITIAL_CAPACITY = 16; /** * HashMap的最大容量,能夠認爲是int的最大值 */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * 默認的加載因子 */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * HashMap用來存儲數據的數組 */ transient Entry[] table;
/** * Constructs an empty <tt>HashMap</tt> with the default initial capacity * (16) and the default load factor (0.75). */ public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR); table = new Entry[DEFAULT_INITIAL_CAPACITY]; init(); }
public V put(K key, V value) { if (key == null) return putForNullKey(value); //處理null值 int hash = hash(key.hashCode());//計算hash int i = indexFor(hash, table.length);//計算在數組中的存儲位置 //遍歷table[i]位置的鏈表,查找相同的key,若找到則使用新的value替換掉原來的oldValue並返回oldValue 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; } } //若沒有在table[i]位置找到相同的key,則添加key到table[i]位置,新的元素老是在table[i]位置的第一個元素,原來的元素後移 modCount++; addEntry(hash, key, value, i); return null; } void addEntry(int hash, K key, V value, int bucketIndex) { //添加key到table[bucketIndex]位置,新的元素老是在table[bucketIndex]的第一個元素,原來的元素後移 Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<K,V>(hash, key, value, e); //判斷元素個數是否達到了臨界值,若已達到臨界值則擴容,table長度翻倍 if (size++ >= threshold) resize(2 * table.length); }
public V get(Object key) { if (key == null) return getForNullKey();//處理null值 int hash = hash(key.hashCode());//計算hash //在table[index]遍歷查找key,若找到則返回value,找不到返回null 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.equals(k))) return e.value; } return null; }
public V remove(Object key) { Entry<K,V> e = removeEntryForKey(key); return (e == null ? null : e.value); } final Entry<K,V> removeEntryForKey(Object key) { int hash = (key == null) ? 0 : hash(key.hashCode()); int i = indexFor(hash, table.length); Entry<K,V> prev = table[i]; Entry<K,V> e = prev; while (e != null) { Entry<K,V> next = e.next; Object k; if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { modCount++; size--; if (prev == e) table[i] = next; else prev.next = next; e.recordRemoval(this); return e; } prev = e; e = next; } return e; }
void resize(int newCapacity) { Entry[] oldTable = table; int oldCapacity = oldTable.length; if (oldCapacity == MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return; } Entry[] newTable = new Entry[newCapacity]; transfer(newTable); table = newTable; threshold = (int)(newCapacity * loadFactor); } void transfer(Entry[] newTable) { Entry[] src = table; int newCapacity = newTable.length; for (int j = 0; j < src.length; j++) { Entry<K,V> e = src[j]; if (e != null) { src[j] = null; do { Entry<K,V> next = e.next; //從新對每一個元素計算index int i = indexFor(e.hash, newCapacity); e.next = newTable[i]; newTable[i] = e; e = next; } while (e != null); } } }
public void clear() { modCount++; Entry[] tab = table; for (int i = 0; i < tab.length; i++) tab[i] = null; size = 0; }
public boolean containsKey(Object key) { return getEntry(key) != null; } final Entry<K,V> getEntry(Object key) { int hash = (key == null) ? 0 : hash(key.hashCode()); 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; }
containsValue方法就比較粗暴了,就是直接遍歷全部元素直到找到value,因而可知HashMap的containsValue方法本質上和普通數組和list的contains方法沒什麼區別,你別期望它會像containsKey那麼高效
public boolean containsValue(Object value) { if (value == null) return containsNullValue(); Entry[] tab = table; for (int i = 0; i < tab.length ; i++) for (Entry e = tab[i] ; e != null ; e = e.next) if (value.equals(e.value)) return true; return false; }
indexFor中的h & (length-1)就至關於h%length,用於計算index也就是在table數組中的下標 hash方法是對hashcode進行二次散列,以得到更好的散列值 爲了更好理解這裏咱們能夠把這兩個方法簡化爲 int index= key.hashCode()/table.length,以put中的方法爲例能夠這樣替換
int hash = hash(key.hashCode());//計算hash int i = indexFor(hash, table.length);//計算在數組中的存儲位置 //上面這兩行能夠這樣簡化 int i = key.key.hashCode()%table.length;
static int hash(int h) { // 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); } static int indexFor(int h, int length) { return h & (length-1); }
爲了加深理解,我我的實現了一個簡化版本的HashMap,注意哦,僅僅是簡化版的功能並不完善,僅供參考
package cn.lzrabbit.structure; /** * Created by rabbit on 14-5-4. */ public class MyHashMap { //默認初始化大小 16 private static final int DEFAULT_INITIAL_CAPACITY = 16; //默認負載因子 0.75 private static final float DEFAULT_LOAD_FACTOR = 0.75f; //臨界值 private int threshold; //元素個數 private int size; //擴容次數 private int resize; private HashEntry[] table; public MyHashMap() { table = new HashEntry[DEFAULT_INITIAL_CAPACITY]; threshold = (int) (DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR); size = 0; } private int index(Object key) { //根據key的hashcode和table長度取模計算key在table中的位置 return key.hashCode() % table.length; } public void put(Object key, Object value) { //key爲null時須要特殊處理,爲簡化實現忽略null值 if (key == null) return; int index = index(key); //遍歷index位置的entry,若找到重複key則更新對應entry的值,而後返回 HashEntry entry = table[index]; while (entry != null) { if (entry.getKey().hashCode() == key.hashCode() && (entry.getKey() == key || entry.getKey().equals(key))) { entry.setValue(value); return; } entry = entry.getNext(); } //若index位置沒有entry或者未找到重複的key,則將新key添加到table的index位置 add(index, key, value); } private void add(int index, Object key, Object value) { //將新的entry放到table的index位置第一個,若原來有值則以鏈表形式存放 HashEntry entry = new HashEntry(key, value, table[index]); table[index] = entry; //判斷size是否達到臨界值,若已達到則進行擴容,將table的capacicy翻倍 if (size++ >= threshold) { resize(table.length * 2); } } private void resize(int capacity) { if (capacity <= table.length) return; HashEntry[] newTable = new HashEntry[capacity]; //遍歷原table,將每一個entry都從新計算hash放入newTable中 for (int i = 0; i < table.length; i++) { HashEntry old = table[i]; while (old != null) { HashEntry next = old.getNext(); int index = index(old.getKey()); old.setNext(newTable[index]); newTable[index] = old; old = next; } } //用newTable替table table = newTable; //修改臨界值 threshold = (int) (table.length * DEFAULT_LOAD_FACTOR); resize++; } public Object get(Object key) { //這裏簡化處理,忽略null值 if (key == null) return null; HashEntry entry = getEntry(key); return entry == null ? null : entry.getValue(); } public HashEntry getEntry(Object key) { HashEntry entry = table[index(key)]; while (entry != null) { if (entry.getKey().hashCode() == key.hashCode() && (entry.getKey() == key || entry.getKey().equals(key))) { return entry; } entry = entry.getNext(); } return null; } public void remove(Object key) { if (key == null) return; int index = index(key); HashEntry pre = null; HashEntry entry = table[index]; while (entry != null) { if (entry.getKey().hashCode() == key.hashCode() && (entry.getKey() == key || entry.getKey().equals(key))) { if (pre == null) table[index] = entry.getNext(); else pre.setNext(entry.getNext()); //若是成功找到並刪除,修改size size--; return; } pre = entry; entry = entry.getNext(); } } public boolean containsKey(Object key) { if (key == null) return false; return getEntry(key) != null; } public int size() { return this.size; } public void clear() { for (int i = 0; i < table.length; i++) { table[i] = null; } this.size = 0; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("size:%s capacity:%s resize:%s\n\n", size, table.length, resize)); for (HashEntry entry : table) { while (entry != null) { sb.append(entry.getKey() + ":" + entry.getValue() + "\n"); entry = entry.getNext(); } } return sb.toString(); } } class HashEntry { private final Object key; private Object value; private HashEntry next; public HashEntry(Object key, Object value, HashEntry next) { this.key = key; this.value = value; this.next = next; } public Object getKey() { return key; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public HashEntry getNext() { return next; } public void setNext(HashEntry next) { this.next = next; } }