Thorough hashCode and hashCode() method

Writing this article is mainly to pave the way for the analysis of the hashCode() method of the String class.

When to use the hashCode value?

HashMap, HashSet, HashTable. Taking HashMap as an example, HashMap needs to perform an AND operation based on the hashCode of the key and (array length - 1) to determine the position of the Entry in the array.

What is the contract of the hashCode() method?

In this article: HashSet Understanding (2) How to ensure that the stored value does not repeat the article, I translated the comments of the hashCode() method and wrote it clearly. Post a brief description:

  • The same object calls the hashCode method multiple times, and the hashCode should return the same value under the premise that the properties compared in equals have not changed.
  • If the equals comparison of two objects is true, then the hashCode values ​​of the two objects must be equal.
  • If the equals comparison of the two objects is false, the hashCode values ​​of the two objects do not have to be different, but it is better to be different, which is beneficial to improve the performance of the hash table.

What requirements does the hashCode value need to meet?

Combining the above questions. It can be concluded that try to ensure that different objects have different hashCode.

What is the difference between the equals() method and hashCode()?

The equals() method returns true and false to determine whether two objects are the same.
The hashCode() method returns a hash integer value, which is mainly used to obtain the position of the object in the hash table (array).

What is the hashCode of capital letter A?

According to the ASCII table , the ASCII value of the capital letter A is 65. According to the above algorithm, h=31*0+65=65. Check whether the code is:

public class CharTest {
    
    
    public static void main(String[] args) {
    
    

        String s = new String("A");
        System.out.println(s.hashCode());
    }
}

output:

65

Add the ASCII value of the characters directly to get the hashCode, okay?

no.
If so, the hashCode values ​​of "AC" and "BB" are the same, and the hashCode values ​​of "AC" and "CA" are also the same.

Guess you like

Origin blog.csdn.net/zhangjin1120/article/details/131600136