本文內容:html
Hash
java
HashMap概述算法
HashMap源碼分析數組
Hash表數據結構
數據結構中都學過Hash,咱們要說的HashMap採用拉鍊法(數組+鏈表)實現。數組具備根據下標快速查找的特色,鏈表動態增長刪除元素。app
(來源:http://www.cnblogs.com/hzmark/archive/2012/12/24/HashMap.html)dom
看上圖,對於HashMap的內部結構應該是一目瞭然了。ide
HashMap概述函數
HashMap是一個Key-Value容器,應該是使用得最多的map了吧。看繼承關係圖源碼分析
HashMap繼承了AbstractMap、Map,實現了Cloneable和Serializable
HashMap源碼分析
看一下HashMap的一些屬性
/** * The default initial capacity - MUST be a power of two. */ static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 /** * The maximum capacity, used if a higher value is implicitly specified * by either of the constructors with arguments. * MUST be a power of two <= 1<<30. */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * The load factor used when none specified in constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * An empty table instance to share when the table is not inflated. */ static final Entry<?,?>[] EMPTY_TABLE = {}; /** * The table, resized as necessary. Length MUST Always be a power of two. */ transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE; /** * The number of key-value mappings contained in this map. */ transient int size; /** * The next size value at which to resize (capacity * load factor). * @serial */ // If table == EMPTY_TABLE then this is the initial capacity at which the // table will be created when inflated. int threshold; /** * The load factor for the hash table. * * @serial */ final float loadFactor; /** * The number of times this HashMap has been structurally modified * Structural modifications are those that change the number of mappings in * the HashMap or otherwise modify its internal structure (e.g., * rehash). This field is used to make iterators on Collection-views of * the HashMap fail-fast. (See ConcurrentModificationException). */ transient int modCount; /** * The default threshold of map capacity above which alternative hashing is * used for String keys. Alternative hashing reduces the incidence of * collisions due to weak hash code calculation for String keys. * <p/> * This value may be overridden by defining the system property * {@code jdk.map.althashing.threshold}. A property value of {@code 1} * forces alternative hashing to be used at all times whereas * {@code -1} value ensures that alternative hashing is never used. */ static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;
其中,實際的元素就存放在table數組裏面。
接着繼續看構造函數
public HashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); } public HashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; threshold = initialCapacity; init(); }
日常咱們都直接調用默認構造函數,默認構造函數調用了HashMap(int initialCapacity,float loadFactor)方法。其中DEFAULT_INITIAL_CAPACITY=16,DEFAULT_LOAD_FACTOR=0.75。咱們看HashMap(int initialCapacity,float loadFactor)主要是給this.loadFactor和threshold賦值,而後調用init()方法,init()方法在HashMap中是空方法。
構造這一步完成的工做是給loadFactor和threshold賦值!
前面說到HashMap的元素存放在table數組。
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
這是個Entry類型的,是HashMap的內部靜態類,其實現了Map.Entry接口。
Map.Entry接口定義以下:
interface Entry<K,V> { K getKey(); V getValue(); V setValue(V value); boolean equals(Object o); int hashCode(); }
HashMap中Entry實現:
static class Entry<K,V> implements Map.Entry<K,V> { final K key; V value; Entry<K,V> next; int hash; /** * Creates new entry. */ Entry(int h, K k, V v, Entry<K,V> n) { value = v; next = n; key = k; hash = h; } //省略 }
能夠看出,Entry有key,value,next,hash這幾個屬性。
put(K key,V value)方法:
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); //遍歷相同hash的元素 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; }
若是table爲空,則調用inflateTable方法擴容。而後,添加元素分兩種狀況:key爲null,key不爲null。
先看一下擴容方法inflateTable(int toSize):
private void inflateTable(int toSize) { // Find a power of 2 >= toSize int capacity = roundUpToPowerOf2(toSize); threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1); table = new Entry[capacity]; initHashSeedAsNeeded(capacity); }
table大小是capacity.後面還調用了initHashSeedAsNeeded方法,它有什麼用呢?
/** * Initialize the hashing mask value. We defer initialization until we * really need it. */ final boolean initHashSeedAsNeeded(int capacity) { boolean currentAltHashing = hashSeed != 0; boolean useAltHashing = sun.misc.VM.isBooted() && (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD); boolean switching = currentAltHashing ^ useAltHashing; if (switching) { hashSeed = useAltHashing ? sun.misc.Hashing.randomHashSeed(this) : 0; } return switching; }
這個,這裏沒看懂要作什麼!先放一下!
繼續看put方法,當key不爲null時,調用hash方法產生一個hash值:
final int hash(Object k) { int h = hashSeed; if (0 != h && k instanceof String) { return sun.misc.Hashing.stringHash32((String) k); } 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); }
Retrieve object hash code and applies a supplemental hash function to the result hash, which defends against poor quality hash functions. This is critical because HashMap uses power-of-two length hash tables, that otherwise encounter collisions for hashCodes that do not differ in lower bits. Note: Null keys always map to hash 0, thus index 0.
大意是說這個算法是減小碰撞(collisions)的,原理求大神告知!!
/** * Returns index for hash code h. */ 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); }
indexFor獲取元素應該存放在那個buket。length-1的緣由是爲了不超出table數據的上界。
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); }
addEntry先判斷要不要擴容。擴容是擴大一倍。而後調用createEntry方法將新元素添加進去。
void createEntry(int hash, K key, V value, int bucketIndex) { Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<>(hash, key, value, e); size++; }
可看出,這是在表頭插入節點。
看下resize 方法,它是如何擴大容器的呢?
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, initHashSeedAsNeeded(newCapacity)); table = newTable; threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1); }
先定義了一個新數組,而後調用transfer將舊元素賦值到新的table上。
void transfer(Entry[] newTable, boolean rehash) { int newCapacity = newTable.length; for (Entry<K,V> e : table) { while(null != e) { Entry<K,V> next = e.next; if (rehash) { e.hash = null == e.key ? 0 : hash(e.key); } int i = indexFor(e.hash, newCapacity); e.next = newTable[i]; newTable[i] = e; e = next; } } }
這裏, rehash做爲一個開關,來控制是否須要從新hash,initHashSeedAsNeeded的做用能夠看到了。是做爲判斷擴容時是否須要rehash的。從transfer方法中也能夠看到爲何HashMap中會有這句說明:
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
HashMap不保證元素的位置,也不保證元素原先的位置不變。
put的方法差很少 了,看下當key爲null時,是如何的
/** * Offloaded version of put for null keys */ private V putForNullKey(V value) { for (Entry<K,V> e = table[0]; e != null; e = e.next) { if (e.key == null) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(0, null, value, 0); return null; }
由addEntry看到,key爲null時,是存放在table的0下標裏面的。
get(Object key)方法:
public V get(Object key) { if (key == null) return getForNullKey(); Entry<K,V> entry = getEntry(key); return null == entry ? null : entry.getValue(); }
get也分爲兩種狀況,key爲null及key不爲null。
先看一下key爲null的狀況:
private V getForNullKey() { if (size == 0) { return null; } for (Entry<K,V> e = table[0]; e != null; e = e.next) { if (e.key == null) return e.value; } return null; }
key爲null在table[0],而後直接鏈表遍歷就能夠了。
當null不爲null時,經過getEntry獲取元素:
final Entry<K,V> getEntry(Object key) { if (size == 0) { return null; } 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; }
先根據hash找出元素在哪一個槽,而後遍歷出該元素。
看下containsKey(Object key):
public boolean containsKey(Object key) { return getEntry(key) != null; }
containsKey(Object key)方法很簡單,只是判斷getEntry(key)的結果是否爲null,是則返回false,否返回true。
(內容太長,oschina不能保存,待續)