Equals () and Hashcode () in Java

Source: Internet
Author: User

Overview

When we use the class set framework (such as using HashMap, HashSet), it often involves rewriting the equals () and Hashcode () methods.

The links between the two methods are:
1. If two objects are different, then their hashcode must be unequal;
2. If two objects have the same hashcode, they may not be equal.

So, if you want to have two unequal objects in the hashmap corresponding to the same value, first need to make their hashcode the same, and then let their equals () method return True, so for this purpose, we can only rewrite hashcode () and Equals () these two methods.

Quote an article on the commentary: the ideabehind a Map is to being able to find a object faster than a linear search. Using hashed keys to locate objects is a two-step process. Internally the Map stores objects as an array of arrays. The index for the first array is the hashcode () value of the key. This locates the second array which are searched linearly by using equals () to determine if the object is found.

The idea is that using a map is faster than a linear search. The map storage object is an array of arrays ( which can be understood as a two-dimensional array, which is not accurate, but can be understood as such.) Before hashmap with an array, each array node corresponds to a linked list, now Java 8 has changed the list to TreeMap, equivalent to a binary tree, so that the retrieval time is faster than the linked list, especially in the worst case, from the original linked list O (n) into a two-tree O (Logn), See Https://dzone.com/articles/hashmap-performance), so the search is generally divided into two steps, the first step is to find the first-dimensional array subscript according to Hashcode, The object is then judged by the return value of equals which is in the second-dimensional array.

Example

Give me a chestnut--

ImportJava.util.HashMap; Public  class Apple {    PrivateString color; Public Apple(String color) { This. color = color; } Public Static void Main(string[] args) {Apple A1 =NewApple ("Green"); Apple A2 =NewApple ("Red");//hashmap stores Apple type and its quantityHashmap<apple, integer> m =NewHashmap<apple, integer> (); M.put (A1,Ten); M.put (A2, -); System.out.println (M.get (NewApple ("Green"))); }}

The program runs with the result: null
At this point, we have stored two objects in HashMap, and A1 is Green Apple, so why do we go through "green" to find but return null?
Obviously, later we come out with a new object, which is definitely not the same object as the A1 green Apple that was added previously, and the return value is definitely not the same as the result of the hashcode () in the ultimate parent class object.

So--

First step: Rewrite Hashcode ()

We need to first make "all the same objects with the same color attribute, whose hashcode are the same", so we can rewrite hashcode () like this:

publicinthashCode(){    returnthis.color.length();}

Here we use the length of the content of the color property as the size of the hashcode, then all green apples, hashcode must be 5 (green string length of 5), so that the properties of the same object hashcode must be the same. This only guarantees that the subscript of one-dimensional arrays is found (let's say so), and you need to find the second-dimension subscript, which needs to be solved in the second step. You might have a problem before you solve the second step--so if there is black Apple (assuming black), then its hashcode is 5, just like green. This is also solved by the second step.

Step Two: Override Equals ()

We already know that if you want to have two objects, except for their hashcode values, let their equals () function return True, and two are equal. So the second step is to rewrite the Equals () function so that "as long as color, two apples are the same":

public  boolean  equals  (Object obj) {if
      (! ( obj instanceof  Apple) //the first type to be the same is possible to return true        Span class= "Hljs-keyword" >return  false ; if     (obj = = this )        //if you are comparing yourself to yourself, it is obviously the same object that returns True  return     true ; return     this . Color.equals (((Apple) obj). color); //if the color is the same, return True }  

In this way, according to the last sentence, the same color of the apple, the second dimension also mapped to the same position (let it be understood). This way, you can search for apples in hashmap by color.
Adding our rewritten hashcode () and Equals () to the previous code will output the result: 10, which is the value of the key A1.

Conclusion

Feel the content of this article is still quite basic and important. Article to this also almost end, another attached to the previous study notes, the feeling is very useful, my own notes look natural is no obstacle, but really do not want to tidy up, just paste it up, we will look at it, can be used as the above content nagging and supplement.

Appendix 1

When the hashset is stored (such as a string), then it is sorted by the hash value (which means that the order is not the order we added, that is, chaos), if the second object is the same as the first hash value but the object is different, the second one will be chained to the first one. When adding an object, add () returns a Boolean, or False if the object being added is the same (for example, two identical strings), adding a failure.

HashSet how to guarantee the uniqueness of elements?
Implemented by means of the element--hashcode () and Equals ().
If the hashcode of the two elements are different, they are saved directly;
If the hashcode of the two elements is the same, then calling equals to determine whether the true,true is the same object is not saved, false proves to be different objects, save it.

Once you have customized the object and want to deposit it into the hashset, be sure to overwrite the hashcode () and Equals () methods--
For example, we define the person class, only contains name,age two parameters, stipulates: As long as the name and age of the same, it is determined to be "the same", you can not deposit hashset, otherwise.
In this case, if we come out of a few people, where the name and age of the same, will be deposited hashset, because these objects are different objects, the memory is not the same, the hash value returned through Hashcode () is not the same, So it's a matter of course deposited hashset. To avoid depositing the "same person" into hashset, we first need to let Hashcode () return the same hash value for the "same person", i.e. overwrite the Hashcode () Method!

publicinthashCode(){    return110;}

This is also possible, but it is not necessary to have all the objects return the same hash value, as long as the "same person" hash value is the same, so write it better:

publicinthashCode(){    return name.hashCode() + age;}

In this case, the hash value returned by the "same person" is the same. However, this is still not perfect, because the hashcode () will allow the "same person" to return the same hash value, but may also allow "different people" to return the same hash value, such as two people name different, age different, but the name of the hash value and age exactly the same, That would be a pit-daddy. To avoid this, the probability that this hash will happen to hit is further reduced, and we write it better:

publicinthashCode(){    return19;}

It is best to multiply the last prime number and so on, can greatly reduce the "different people" the probability of the hash hit.
With the overwrite of the above hashcode () function, we have the same hash value for the "same person", then we will overwrite the Equals () function! Since Java encounters the same hash value, the next step is to determine whether two objects are the same according to the Equals () function, and the same is no longer stored in hashset, and is stored in a chain of objects with the same hash value (chained to a string).

Appendix 2: The following is the TreeSet content, and the above relationship is not big

TreeSet can sort the elements inside, such as if the object is a string, sorted by dictionary order.

if you want to save a custom object, you need to make the custom objects comparable so that TreeSet can sort them in a certain order. Otherwise, an exception is reported. In order for a custom object to be comparable, the object needs to implement the comparable interface.
For example, there is a person class, we want to new out some people put into the treeset, in order to make the object comparable so as to be able to deposit treeset, we specify according to the age of the object order.
First, let the person class implement the comparable interface, overwrite the interface's CompareTo () method, whose return value is the same as the C language's strcmp ():

In this case, if the age of the two objects is the same, then the later person will not be credited to the TreeSet because the later is considered to be the same object as the previous one.
So we have to sort the primary keyword after the second keyword is sorted, only if all the keywords are finished or return 0, we can consider the two objects the same.
So the CompareTo () should look like this:

 Public int CompareTo(Object obj) {//The need to pass in is the object type, which should be noted    if(! (objinstanceofperson)) {//Pass in the wrong object, throw the exception directly        Throw NewRuntimeException ("Not the same Kind of object!"); } person P = (person) obj;//Transform objects down    if( This. Age < P.age)return-1;if( This. Age > P.age)return 1;if( This. Age = = P.age) {return  This. Name.compareto (P.name);An empty Method CompareTo () in the//string class that is covered by the comparable interface, sorting the strings by dictionary order}}

So if you want TreeSet to keep the data in the input order instead of sorting it automatically, you can override the CompareTo () method like this:

publicintcompareTo(Object obj){    return1;}

It is simple, but the flaw is that "the same person" will also be stored in. This function is completely in the order of the input content without any deletion of the original sequence in the original order TreeSet.
Similarly, if return-1 is the inverse of the input order, return 0 can only be credited to the first input object.

The above is the first method of TreeSet ordering-to make the element itself comparable ( let the class implement the comparable interface, overwrite the CompareTo () method ).
However, this method is flawed, for example, I suddenly do not want to follow the age row, want to sort by name, this need to re-modify the code.

So the second method of TreeSet ordering--making the collection itself a comparison ( passing a custom comparer to the TreeSet constructor ).
For example, we should now sort by the dictionary of names:
First build a comparator, implement the comparator interface, overwrite the Compare () method (The return value is the same as strcmp ()):

 PublicPersoncomparemethod Implements comparator{ Public int Compare(Object Obj1, Object obj2) {//Pass in two object objectsperson P1 = (person) obj1;//Down Transformationperson P2 = (person) obj2;intnum = P1.getname (). CompareTo (P2.getname ());///Directly compare the dictionary order of two strings, because the string class has already covered the comparable interface's empty method CompareTo () to sort the strings by dictionary order        if(num = =0){return NewInteger (P1.getage ()). CompareTo (NewInteger (P2.getage ()));//This is a very clever sentence!!! Originally we can directly according to the number size comparison age this secondary keyword, but in comparison, we replaced a more high-end method: Two new integer object, because there is also the CompareTo () method, the number is compared in dictionary order. Of course, the implementation of the comparable interface and overwrite the CompareTo () method to have such a function}returnNum }}

Then, pass our constructor to the constructor that is called when you treeset the new object:
TreeSet ts = new TreeSet(new MyCompareMethod());

Use the second way:
Objects are not comparable, or comparisons are not what we need.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Equals () and Hashcode () in Java

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.