Hashmap implementation principle

Source: Internet
Author: User
Document directory
  • Entry. Java
  • Myhashmap. Java
  • Myhashmaptest. Java
0. References:

Hash Algorithm (hashmap implementation principle)

JAVA Implementation hash

1. Data Structure of hashmap

  ArrayFeatures: Easy addressing, difficult insertion and deletion; andLinked ListIt is characterized by hard addressing and easy insertion and deletion. So can we combine the two features to make a data structure that is easy to address and easily inserted and deleted? The answer is yes. This is what we want to mention.Hash tableHash Tables have different implementation methods. What I will explain next is the most commonly used method-the zipper method, which can be understood as"Array of linked list",

We can find that the hash table is composed of arrays and linked lists. In an array with a length of 16, each element stores a head node of the linked list. So what rules are these elements stored in the array. It is generally obtained through Hash (key) % Len, that is, the hash value of the element's key is modeled on the array length. For example, in the hash table above, 12% 16 = 12,108%, 12,140% = 16 = 12. Therefore, 12, 28, 108, and 140 are stored at the position where the array subscript is 12.

Hashmap is actually a linear array, so it can be understood that the container for storing data is a linear array. This may make us puzzled. How does a linear array implement key-value pairs to access data? Here, hashmap does some processing.

1. first, a static internal class entry is implemented in hashmap. Its important attributes include key, value, next, from attribute key, value, we can see that entry is a basic bean implemented by the hashmap key-value pair. We mentioned above that the basis of hashmap is a linear array, and this array is entry [], the content in map is saved in entry.

2. Access Implementation of hashmap

Why Random Access to Linear Arrays? Here hashmap uses a small algorithm, which is roughly implemented as follows:

// Int hash = key. hashcode (); // This hashcode method is not detailed here, as long as you understand that the hash of each key is a fixed int value int Index = hash % entry []. length; entry [Index] = value; // value: int hash = key. hashcode (); int Index = hash % entry []. length; return entry [Index];

Here, we can easily understand the basic principle of access through key-value pairs in hashmap.

3. Q: Is there any risk of overwriting if the two keys have the same index through hash % entry []. length?

Here, hashmap uses the concept of chained data structure. As mentioned above, the entry class has a next attribute to point to the next entry. For example, if the first key-value pair a comes in, calculate the hash value of its key to obtain Index = 0, and record it as entry [0] =. After a while, another key-Value Pair B will be added. Its index is equal to 0 after calculation. What should I do now? Hashmap will do this: B. next = A, entry [0] = B. If C is introduced and index is equal to 0, C. next = B, entry [0] = C; in this way, we find that index = 0 actually accesses three key-value pairs A, B, and C, they are linked together through the next attribute. So don't worry.That is to say, the array stores the last inserted element.By now, we should be clear about the implementation of hashmap.

Of course, hashmap also contains some optimization implementations. For example, after entry [] has a certain length, as the data in the map grows, the chain of the same index will be long, will it affect the performance? Set a factor (also known as a factor) in hashmap. As the size of map increases, entry [] will extend the length according to certain rules.

3. Solution to hash conflicts
  1. Open addressing method (linear detection is re-hashed, secondary detection is re-hashed, and pseudo-random detection is re-hashed)
  2. Rehash
  3. Link address Method
  4. Create a public overflow Zone

The hashmap solution in Java is the link address method.

4. Implement your own hashmap

 

Entry. javaview code

Package Edu. SJTU. erplab. hash; public class entry <K, V> {final K key; V value; entry <K, V> next; // next node // constructor public entry (K, V v, entry <K, V> N) {key = K; value = V; next = N;} 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 entry) return false; entry E = (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 ();}}
Myhashmap. javaview code

Package Edu. SJTU. erplab. hash; // ensure that the key and value are not empty public class myhashmap <K, V> {private entry [] Table; // entry array table static final int default_initial_capacity = 16; // default array length private int size; // constructor public myhashmap () {table = new entry [default_initial_capacity]; size = default_initial_capacity ;} // obtain the array length public int getsize () {return size;} // obtain the index static int indexfor (int h, int length) {return H % (Length-1);} // obtain the public v get (Object key) {If (Key = NULL) return NULL; int hash = key. hashcode (); // The hash value of the key int Index = indexfor (hash, table. length); // evaluate the subscript of the key in the array for (Entry <K, V> E = table [Index]; e! = NULL; E = E. next) {object K = E. key; If (E. key. hashcode () = hash & (k = Key | key. equals (k) Return e. value;} return NULL;} // Add the public v put (K key, V value) {If (Key = NULL) return NULL; int hash = key. hashcode (); int Index = indexfor (hash, table. length); // If the added key already exists, you only need to change the value to for (Entry <K, V> E = table [Index]; e! = NULL; E = E. next) {object K = E. key; If (E. key. hashcode () = hash & (k = Key | key. equals (k) {v oldvalue = E. value; E. value = value; return oldvalue; // Original Value }}// if the key value does not exist, add entry <K, V> E = table [Index]; // obtain e table [Index] = new entry <K, V> (Key, value, E) in the current array; // create an entry, and point it to the original E return NULL ;}}
Myhashmaptest. javaview code

package edu.sjtu.erplab.hash;public class MyHashMapTest {    public static void main(String[] args) {        MyHashMap<Integer, Integer> map = new MyHashMap<Integer, Integer>();        map.put(1, 90);        map.put(2, 95);        map.put(17, 85);            System.out.println(map.get(1));        System.out.println(map.get(2));        System.out.println(map.get(17));        System.out.println(map.get(null));    }}

 

 

 

 

 

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.