HashMap source code analysis

Source: Internet
Author: User

HashmapSource code analysis

Author: 10 years of firewood Writing Date: 2011-9-26

Hashmap is a container class that is frequently used in Java. It is also frequently asked during Java test interviews. A deep understanding of hashmap helps us better use it.

1. hashmapInternal Structure

Understanding the data structure of hashmap helps you understand various operations of hashmap. The internal structure of hashmap is as follows:

static final int DEFAULT_INITIAL_CAPACITY = 16;
static final float DEFAULT_LOAD_FACTOR = 0.75f;

Initialize a hashmap class. You can specify a capacity parameter initialcapacity. The constructor initializes the Class Based on initialcapacity and finds a value greater than or equal to initialcapacity and is an integer power of 2 as the length of the hash array:

int capacity = 1;
while (capacity < initialCapacity)
capacity <<= 1;
this.loadFactor = loadFactor;
threshold = (int)(capacity * loadFactor);
table = new Entry[capacity];

Elements stored in hashmap are entry classes, which are internal classes defined in hashmap:

static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
final int hash;
}

Here, key is the saved key value, value is the saved value, next is the pointer to the next entry element, and hash is the hash value of the hashcode of the key.

2. hashmapVarious operations in

Insert operation put:

Public v put (K key, V value ){
If (Key = NULL)
Return putfornullkey (value );
Int hash = hash (key. hashcode (); // re-hash the hashcode value of the key
Int I = indexfor (hash, table. Length); // locate the position where the key is placed in the table.
For (Entry <K, V> E = table [I]; e! = NULL; E = E. Next ){
// Check whether the internal key exists. If yes, update its value.
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); // Add the new Entry <key, value> to the table
Return null;
}

The Insertion Algorithm specially deals with the case where the key is null. HashMap inserts the null key value into the linked list at a location in the table array. HashMap uses the following algorithm for hash:

static int hash(int h) {
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}

The addEntry algorithm inserts Entry <key, value> into the head of the linked list:

void addEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
if (size++ >= threshold)
resize(2 * table.length);
}

After the element is inserted, check whether the elements in the array exceed the threshold (array length * loading Factor). If the limit is exceeded, the extended array length is twice the original length, and re-hash the elements of the original array, and put them into the new position in the new array.

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);
}
/* Transfers all entries from current table to newTable */
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;
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
} while (e != null);
}
}
}

Array Space reallocation and array element re-hash are time-consuming. Therefore, when HashMap is used, if you can predict the approximate range of the number of elements to be stored, you can specify the array length when initializing a HashMap to effectively avoid re-hashing. The following describes how HashMap can be quickly selected:

Public V get (Object key ){
If (key = null)
Return getForNullKey (); // retrieves the value from the linked list where the first element of the array is located.
Int hash = 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. equals (k )))
Return e. value;
}
Return null;
}

If the key is null, the hash method is used to locate the position in the array where the key is located, and then traverse the corresponding linked list.

Traversal operation:

Because the storage location of elements in hashMap is irrelevant to the insertion sequence, during the traversal, hashMap does not guarantee that the traversal results are consistent with the insertion sequence.

Hashmap usually uses keyset and entryset for traversal. The keyset Traversal method converts the key value of the element set into a set. The Code is as follows:

Map map = new HashMap();
  Iterator iter = map.keySet().iterator();
  while (iter.hasNext()) {
   Object key = iter.next();
   Object value = map.get(key);
  }

Entryset converts the entry stored in hashmap to entryset. The Traversal method is as follows:

 for(Map.Entry<Integer, String>m:map.entrySet()){
Object key=m.getKey();
Object value=m.getValue();
}

The two traversal methods differ in efficiency: ketset traverses the Element Set twice, converts the element set to keyset for the first time, and passes the map for the second time. get (key) has been traversed once; entryset traversal only once, so it is more efficient than the former.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.