Equals () and Hashcode () in Java

Source: Internet
Author: User

Overview

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

The links between the two methods are:
1. Assuming that two objects are different, then their hashcode must not be equal;
2. Assume that the hashcode of two objects is the same. Then they are not necessarily equal.

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

Quote an article explaining: the ideabehind a Map are 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. This is not accurate, just can follow this understanding. The previous hashmap used an array. Each array node corresponds to a linked list. Now Java 8 has changed the list to TreeMap. Equivalent to a binary tree. This is faster than the linked list, especially in the worst case, the O (n) from the original list becomes the O (Logn) of the two fork tree, see Https://dzone.com/articles/hashmap-performance). So the search is roughly two-step, the first step is to find the subscript for the first-dimensional array based on hashcode, and then infer from the return value of equals which of the second-dimensional arrays.

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 execution result of the program is: 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. Then 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 let "all the same object with the color attribute, its hashcode is the same", so we can rewrite Hashcode ():

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 apple, hashcode must be 5 (green string length of 5), so that the properties of the same object hashcode must be the same. This is only to ensure that the subscript of one-dimensional array is found (let's say so), but also need to find a second-dimensional subscript, which needs to be resolved in the second step. You may have a problem before you solve the second step--that is. Assuming there is a black apple (assuming black), then its hashcode becomes 5, just like green. This is also solved by the second step.

Step Two: Override Equals ()

We already know. Suppose you want to have two objects, except for their hashcode values, to return true for their equals () function, and two to match.

So the second step is to rewrite the Equals () function so that "just a color, two apples is the same":

public  boolean  equals  (Object obj) {if
      (! ( obj instanceof  Apple) //first type is also possible to return true        Span class= "Hljs-keyword" >return  false ; if     (obj = = this ) //assumed to be himself compared with himself.    is obviously the same object, which returns true  return  true ; return     this . Color.equals (((Apple) obj). color); //assumes the same color, also returns True }  

In this way, according to the last sentence. Any apple with the same color. The second dimension also maps to the same location (let's just say so). In this way, you can find apples in hashmap based on color.
Adding our rewritten hashcode () and Equals () to the previous code will output the result: 10, which is the corresponding value of the key A1.

Conclusion

Feel the content of this article is still quite basic and important.

The article is almost as close to the end of the story. Also attached to the note that once study, feel is quite practical, my own notes look natural is no obstacle, just really do not want to tidy up, directly affixed to it, we will look at it, can be as above the content of the nagging and supplement.

Appendix 1

The hashset is stored (for example, a string). Then they are sorted according to the hash value (which means that the order of the traversal is not the order we added, that is, the chaos), assuming that the second object is the same as the first hash value but the object is different, then the second one will be chained to the first one. When adding an object, add () returns a Boolean, assuming that the added object is the same (for example, two identical strings), then false is returned. Join failed.

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

Once you have defined the object. To deposit into the hashset, be sure to overwrite the hashcode () and Equals () methods--
For example, we define the person class, which contains only name,age two parameters. provisions: Only the name and age of the same, it is determined to be "the same person", you can not deposit hashset, otherwise the words can.
For this situation. Suppose we new out a few people, the existence of the name and age of the same, will be deposited hashset. The reason is that 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, just like the "same person" hash value, so write it better:

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

The same is true of the hash value returned by the "same person". Just this is still not perfect. Since the hashcode () override will allow "the same person" to return the same hash value, it may also allow "different people" to return the same hash value. For example, two person name is different, age is different. But the hash value of name plus age is exactly the same, and that's what it's like to be a dad. 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, which can greatly reduce the probability of hitting the hash value of "different people".


Overwrite by the above hashcode () function. We have the same hash value for the "same person", so the next step is to overwrite the Equals () function. Since Java encounters the same hash value, the next step is to infer from the Equals () function whether the two objects are the same, the same is no longer deposited into the hashset, the different words are stored, and the chain is on the same object as its hash (chained to a string).

Appendix 2: Below is the treeset content. It's not much of a relationship.

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

Suppose you want to save your own definition object, you need to make your own definition of the object to be relatively comparative. Such words treeset ability to sort them according to certain order.

Otherwise, an exception is reported. In order for you to define the object can be relatively comparative. The object needs to implement the comparable interface.
For example, there is a person class. We're going to get new out. Some people put in treeset, in order to make the object comparable so as to be able to deposit TreeSet. We set the order according to the age of the object.
First, let the person class implement the comparable interface, overwrite the interface's CompareTo () method. The return value is the same as the C language strcmp ():

Such words. Assuming that the age of the two objects is the same, then the later person will not be credited to the TreeSet, since the latter is thought to be the same object as the previous one.
So we must sort the secondary keywords after the primary key is sorted. Only if all the keywords are more complete or return 0, we can think of two objects the same.


So the CompareTo () should be this:

 Public int CompareTo(Object obj) {//Pass in the required object type, this should be noted    if(! (objinstanceofperson)) {//The object passed in is incorrect and throws an 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);the Empty Method CompareTo () of the comparable interface is covered in the//string class. Sort strings According to the dictionary order}}

So, let's say you want TreeSet to keep the data in the order of entry, rather than actively sort by yourself. The ability to overwrite the CompareTo () method is as follows:

publicintcompareTo(Object obj){    return1;}

Very easy, but the flaw is that "the same person" will also be stored in. This function is completely in accordance with the order of the input content, no matter what the original sequence of the deletion of TreeSet.
Similarly, suppose return-1 is the inverse of the input order, assuming that return 0 is only able to deposit 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 ).


It's just that the scheme is flawed, for example, I suddenly don't want to follow the age line and want to sort by name. This will require another change in the code.

So another way to sort the treeset--to make the collection itself comparable (the constructor that passes its own definition to the TreeSet).


For example, we are now going to sort by the dictionary order of names:
First build a comparison device. 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 compared to the dictionary order of two strings, because the string class has already covered the empty method CompareTo () of the comparable interface. Sort strings According to the dictionary order        if(num = =0){return NewInteger (P1.getage ()). CompareTo (NewInteger (P2.getage ()));//This is a clever sentence!!! Originally we can directly according to the size of the digital age of the secondary keyword, but in comparison, we replaced a relatively high-end method: Two new integer object, because there are CompareTo () method in the integer class. Compare numbers according to the dictionary order.

当然是实现了Comparable接口并覆写compareTo()方法才具有这种功能 } return num; }}

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

Use a different approach:
Object does not have a comparability. Or the comparability is not what we need.

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.