Java-15.7 Map (3)-Introduction to the working principle of HashMap-get Method

Source: Internet
Author: User

Java-15.7 Map (3)-Introduction to the working principle of HashMap-get Method

Next we will discuss the get method in the previous chapter.

1. Use the diagram in the previous chapter.

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

To put it simply, we use hashcode to first locate the position on the table and then traverse the linked list at the position.

 

2. source code of the get method:

 

public V get(Object key) {        if (key == null)            return getForNullKey();        int hash = hash(key.hashCode());        for (Entry
 
   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;    }
 

Explanation:

 

(1) when the key is null, use a specific method to get this element.

Source code of getForNullKey:

 

 private V getForNullKey() {        for (Entry
 
   e = table[0]; e != null; e = e.next) {            if (e.key == null)                return e.value;        }        return null;    }
 

From the source code, we can see that e = table [0], e is the first element to take the table, and once again proves our previous conclusion that the key is a null element, is directly placed in the first position of the table.

(2) Calculate the hashcode of the key and then use the hash method.

 

(3) locate the position on the table

 

(4) traverse table and find corresponding elements (in addition to comparing hashcode, we also need to use the equals method)

Summary: This chapter is relatively simple, because get is basically the reverse operation of put.

This chapter is here. Thank you.

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.