Understanding of ==, equals() and hashCode() in Java

The difference between == and equals()

==: Basic data types compare values, and reference data types compare memory addresses;
equals():
1. When the class does not override the equals() method, it is equivalent to "== ";
2. The class is rewritten In the equals() method, the content used to compare objects is generally rewritten.
For example, the equals() method in the frequently used String type data is used to determine whether the string values ​​are equal (the equals() method in the String class is overridden, and the equals() in the Object class is the memory of the comparison object address)

hashCode ()

The function of hashCode() is to obtain the hash code of the object (actually an int integer). The function of this hash code is to determine the index position of the object in the hash table (hash table, key-value pair form) ;
1. If two objects are equal, then their hashCode() values ​​must be the same;
2. If two objects have the same hashCode(), they are not necessarily equal.
Note : This is the case in the hash table. This must be the case in non-hash tables!

Why must the hashCode method be rewritten when rewriting equals?

To manipulate objects in HashSet, if the hashCode method is not overridden in the object class, the hashCode of the newly created object will be different, and there will be duplicate objects
in the HashSet. This can be reflected in the principle of HashSet de- duplication . When you add the object to the HashSet, HashSet The hashcode value of the object is first calculated to determine the position where the object is added, and it is also compared with the hashcode value of other objects that have been added at that position. If there is no matching hashcode, HashSet will assume that the object does not appear repeatedly. But if an object with the same hashcode value is found, the equals() method will be called to check whether the objects with equal hashcode are really the same. If the two are the same, HashSet will not let it be added successfully. If they are different, they will be hashed to another location. (The second edition of "Head first java"). In this way, we have greatly reduced the number of equals, and correspondingly increased the execution speed.

Guess you like

Origin blog.csdn.net/weixin_43278644/article/details/110739293