The implementation principle of Android interview HashMap

Source: Internet
Author: User
Tags modulus

1. The difference between HashMap and Hashtable
    • HashMap allows key and value to be null;

    • HashMap is non-synchronous, thread insecure, or Collections.synchronizedmap () method can be used to get a synchronized HashMap

    • HashMap faster access and high efficiency

    • HashMap removed the contains method in the Hashtable, plus the Containsvalue and ContainsKey methods

2, the realization principle of HashMap

A word to understand hashmap:hashmap is the hash table map implementation. Hash table is a hash array, map implementation refers to the implementation of the map interface.

    1. Data structure of HashMap

      The bottom of the HashMap is based on arrays and linked lists, and the reason for fast storage is that it determines the location of the store by calculating the hash code. HashMap is mainly through the key hashcode to calculate the hash value, as long as hashcode the same, the calculated hash value is the same. If you store more objects, it is possible that different objects will have the same hash value, and there is the so-called hash conflict. There are many ways to solve the hash conflict, and the bottom of the hashmap is to solve the hash conflict through the linked list.

HashMap in entry class source

Static Class Entry<k,v> implements Map.entry<k,v> {

Final K Key;

V value;

Entry<k,v> Next;

final int hash;

Entry (int h, K K, v V, entry<k,v> N) {

Value = V;

Next = n;

key = k;

hash = h;

}

Public final K GetKey () {

Return key;

}

Public final V GetValue () {

return value;

}

Public Final v SetValue (v newvalue) {

V OldValue = value;

value = newvalue;

return oldValue;

}

Public final Boolean equals (Object o) {

if (! ( o instanceof map.entry))

return false;

Map.entry e = (map.entry) o;

Object K1 = GetKey ();

Object K2 = E.getkey ();

if (k1 = = K2 | | (K1! = null && k1.equals (K2))) {

Object v1 = GetValue ();

Object v2 = E.getvalue ();

if (v1 = = V2 | | (V1! = null && v1.equals (v2)))

return true;

}

return false;

}

Public final int hashcode () {

Return (Key==null 0:key.hashcode ()) ^

(Value==null 0:value.hashcode ());

}

Public final String toString () {

return GetKey () + "=" + GetValue ();

}

void Recordaccess (hashmap<k,v> m) {

}

void Recordremoval (hashmap<k,v> m) {

}

}

HashMap is actually a entry array, entry object contains the key and the value, where next is also a entry object, it is used to deal with the hash conflict, form a linked list.

2. Several variables of HashMap

Transient entry[] table;//storage Entry Array

transient int size;//The number of entry stored

int threshold;//The lower limit, the threshold value, the array length exceeds this value will enlarge, threshold = loadfactor* capacity;

Final float loadfactory;//load factor, the larger the load factor, the more elements the current array fills up, the higher the space utilization, the less convenient the query, the smaller the loading factor, the less the fill element, the lower the space utilization, and the faster the convenience. The default value is 0.75;

transient int modcount;//number of times modified

3. Construction method of HashMap

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); Find a power of 2 >= initialcapacity

int capacity = 1;

while (Capacity < initialcapacity)

Capacity <<= 1; This.loadfactor = Loadfactor;

threshold = (int) (capacity * loadfactor);

Table = new Entry[capacity];

Init ();

}

Allows us to specify our own initial capacity and load factor

Public HashMap (Int. initialcapacity) {This (initialcapacity, default_load_factor);

}

Only the initial capacity is specified, and the load factor uses the default of 0.75;

Public HashMap () {this.loadfactor = Default_load_factor;

threshold = (int) (default_initial_capacity * default_load_factor);

Table = new Entry[default_initial_capacity];

Init ();

}

The initial capacity and load factor all use the default value, the default initial load capacity is 16, the load factor is 0.75;

4. Storing the data put method

Public V put (K key, V value) {

if (key = = null)

return Putfornullkey (value);

int hash = hash (Key.hashcode ());

int i = indexfor (hash, table.length);

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;

}

Can be seen, HashMap storage data, will first get the key hashcode value, the hash operation, get the specific hash value, and then based on the hash value to find the location of storage, find the location, and then traverse the table array to find the corresponding position of the entry, If the current key already exists and the hash value of the entry is the same as the key, then the value is updated, otherwise the key and value value are added to the array;

Note here: Judging whether the 2 entry is the same, you need to judge from 2 aspects: 1, 2 entry must be the same key (k = e.key| | Key.equals (k)), 2, 2 entry hashcode, that is, the hash value must be the same (here the hash is after the hash (hashcode) conversion value), the above 2 conditions are satisfied, can be determined that the current entry already exist, The new entry will replace the old entry.

The 2 methods involved in the put process are given below

-Implementation of hash code according to Hashcode

static int hash (int h) {

H ^= (H >>>) ^ (h >>> 12); Return h ^ (H >>> 7) ^ (H >>> 4);

}

-The index stored in the array according to the hash code

static int indexfor (int h, int length) {//The index value is calculated based on hash value and array length 2 return H & (length-1);//This can not be arbitrarily calculated, with hash& (LENGTH-1) is a This ensures that the calculated index is within the array size range and will not exceed 3}

Here are some classmates curious, why index value is H & (length-1)? In fact, there are quite a lot of stories. Generally hash table hash we will use the hash value of the length modulus, Hashtable is implemented, this method can ensure that the elements in the hash table is evenly dispersed, but the modulus will be used to divide the operation, the efficiency is very low, HashMap is the hashtable to improve the implementation, In order to improve efficiency, the use of h& (length-1) to replace the division operation, on the basis of uniform hashing to maintain the efficiency of the increase.

5. Resize method

Used to re-enlarge the size of the reduced 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);

}

In fact, it is to create a large array, the original data added back in. When will the resize method be triggered? When the number of current elements reaches the Loadfactor (default 0.75) of the total size of the array, the resize method is called, enlarging the array to twice times the original size;

6. HashMap's Get method

Public V get (Object key) {

if (key = = null)

return Getfornullkey ();

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;

}

Can see, first get the key hashcode, find the hash code, according to the hash code to locate the index, and then go to the array to get the corresponding index element, if the key is the same hash, key is the same, then this is the entry we are looking for, It's OK to return the value of the entry.

If you feel good, we reproduced at the same time, also point to the bottom of the article "Androiddeveloper" subscription button, pay attention to "Androiddeveloper"

The implementation principle of Android interview HashMap

Related Article

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.