java-15.7 Map (2)-Introduction to how HashMap works-put method

Source: Internet
Author: User

In this chapter we introduce how HASHMAP works.

1.HashMap Working principle Diagram

Referenced from: http://www.admin10000.com/document/3322.html


2.HashMap initialization We can understand this: an array, each location is a linked list, each element of the list is the element of our record


3. Let's look at the source of the put:

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;    }

Explain:

A. When key is empty, use the Putfornullkey method to place the element at the very beginning. Note: HashMap is allowed to empty the key. The following code is proof:

Package Com.ray.ch15;import Java.util.hashmap;public class Test {public static void main (string[] args) {hashmap< String, string> map = new hashmap<string, string> (), Map.put (null, "1");}}


B. When key is not empty, you need to calculate the hashcode of key, because the Hashcode () method inherits object, so each key has this method. Of course, we can also rewrite the hashcode (), but there will be a series of problems, and we'll start with the later chapters.

Note: There is a hash () method, that is, the key hashcode once again hash, this is mainly to make this hash code more evenly distributed, the following is the source of the hash:

static int hash (int h) {        //This function ensures, hashcodes that differ-only to        //constant multiples at each Bit position has a bounded        //number of collisions (approximately 8 at default load factor).        H ^= (H >>>) ^ (h >>> N);        Return h ^ (H >>> 7) ^ (H >>> 4);    }

We then calculate where this series of elements is placed on the big table by Indexfor.


D. When we have finished calculating the position of the list above the table, we need to traverse the above element, so there is a for loop.


Extension (1): Here we need to highlight the above-mentioned table,table source code:

/**     * The table, resized as necessary. Length must always be a power of.     */    transient entry[] table;

It is an array of entry, and this entry is the element we put into it.

This table is the 1,2,3,4 on the y-axis of our left ... it is a list of entry that is recorded in every location.

As you can see from the note, this table is mutable, and when the map's capacity exceeds a certain limit, he triggers the Resize method, creates a new table from scratch, and copies a copy of the data to a newer one. Here is the source code for 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);        Table = newtable;        threshold = (int) (newcapacity * loadfactor);    }

Extension (2): When it comes to table, we must load the factor (Default_load_factor) with another important parameter. The following is the load factor initialization value, 0.75, which means that when map capacity reaches 0.75, the resize method will be triggered to re-scale the map size. The value of this factor determines the performance of a large number of maps, which are explained later in the chapter.

/**     * The load factor used when none specified in constructor.     */    static final float default_load_factor = 0.75f;


4. In summary, the map's put process is:

(1) Check if key is empty

(2) Calculate the hashcode of the key and the index (position) in the table

(3) Find the element above the table

(4) Traversing linked list, if not put in, there is update



Summary: In this chapter, we mainly introduce the working principle of HashMap by put method.


This chapter is here, thank you.

-----------------------------------

Directory


java-15.7 Map (2)-Introduction to how HashMap works-put method

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.