Equals method and hashcode Method

Source: Internet
Author: User

Why the equals and hashcode methods are used?
Equals: Sometimes we need to closely compare whether two objects are equal (manually called by ourselves)
Hashcode: it is because we want to save the unique object to the Collection (or there cannot be duplicate values in the actual collection, and we also need to compare whether there are duplicates, for example, hashset and hashmap keys) (ProgramSelf-called)

The equals of an object compares the memory addresses of two objects. The hashcode method returns a hash code value related to the memory address, which is an int value,
However, the hashcode MethodAlgorithmIt is related to the object itself (JDK calculates it based on the object address, string, or number). So when you rewrite equals, the object itself changes, of course, the hashcode also changes (the hashcode method defined by the object class will return different integers for different objects)

A

Before Rewriting:

 Package  Collectionsframework;  Import  Java. util. hashmap;  Import  Java. util. hashset;  Import Java. util. iterator;  Import  Java. util. Map;  Import  Java. util. Map. entry;  Public   Class  Hashsettest {  Public   Static   Void  Main (string [] ARGs) {Map <Student, string> M = New Hashmap <student, string> (); M. Put ( New Student (1, "zhangsan"), "AA" ); M. Put (  New Student (1, "zhangsan"), "BB" ); M. Put (  New Student (2, "differentiated"), "cc" ); System. Out. println (  New Student (1, "zhangsan") = New Student (1, "zhangsan" ); System. Out. println (  New Student (1, "zhangsan"). Equals ( New Student (1, "zhangsan"); Iterator <Entry <student, string> itmap = M. entryset (). iterator ();  While  (Itmap. hasnext () {system. Out. println (itmap. Next ());  System. Out. println (M. Get (new student (1, "zhangsan ")));  } System. Out. println (); hashset <Student> HS = New Hashset <student> (); HS. Add (  New Student (1, "zhangsan" ); HS. Add ( New Student (1, "zhangsan" ); HS. Add (  New Student (2, "differentiated" ); Iterator <Student> itset = HS. iterator ();  While  (Itset. hasnext () {system. Out. println (itset. Next ());  System. Out. println (M. Get (new student (1, "zhangsan ")));  }  /* * For (iterator it = m. entryset (). iterator (); it. hasnext ();) {* system. out. println (M. get (new student (1, "zhangsan ")));}  */  }}  Class  Student {  Int  Num; string name; student (  Int  Num, string name ){  This . Num = Num;  This . Name = Name ;} Public  String tostring (){  Return Num + "+" + name + "+" + This . Hashcode () + ";" ;}} 

Result:

 
False
False
1 + zhangsan+ 33263331; = bb
Data obtained through the key: ------- null
1 + zhangsan+ 12677476; = AA
Data obtained through the key: ------- null
2 + differentiation + 6413875; = cc
Data obtained through the key: ------- null

1 + zhangsan + 28737396;
Null
1 + zhangsan + 27744459;
Null
2 + differentiation + 6927154;
Null


B

Only override equals

 Package  Collectionsframework;  Import Java. util. hashmap;  Import  Java. util. hashset;  Import  Java. util. iterator;  Import  Java. util. Map;  Import  Java. util. Map. entry;  Public   Class  Hashsettest {  Public   Static   Void Main (string [] ARGs) {// same as above  }}  Class  Student {  Int  Num; string name; student (  Int  Num, string name ){  This . Num = Num;  This . Name = Name ;}  Public  String tostring (){ Return Num + "+" + name + "+" + This . Hashcode () + ";" ;}  Public   Boolean  Equals (Object OBJ ){  If ( Null = OBJ ){  Return   False  ;}  Else  { If (OBJ Instanceof  Student) {student O = (Student) OBJ;  If ( This . Name = O. Name && This . Num = O. Num ){  Return   True  ;}}  Return   False ;}}} 

Result:

 
False
True
1 + zhangsan+ 33263331; = bb
Data obtained through the key: ------- null
1 + zhangsan+ 12677476; = AA
Data obtained through the key: ------- null
2 + differentiation + 6413875; = cc
Data obtained through the key: ------- null

1 + zhangsan + 28737396;
Null
1 + zhangsan + 27744459;
Null
2 + differentiation + 6927154;
Null


New student (1, "zhangsan "). equals (new student (1, "zhangsan") is true, but both 'identical 'objects are used as the key values of hashmap and are stored in hashset. Why? Because JDK is not a simple equals like yours, when comparing two objects, it will also compare the hash code value of the object. Only when hashcode () is overwritten and the hashcode is consistent will they be equal, in this case, hashset contains data that we think is duplicated. hashmap has the same key. When we use the same key to retrieve the value, the program does not know which key you call, so the value cannot be found, and the junk hashset and hashmap appear.

C

Only override hashcode

 Package  Collectionsframework;  Import Java. util. hashmap;  Import  Java. util. hashset;  Import  Java. util. iterator;  Import  Java. util. Map;  Import  Java. util. Map. entry;  Public   Class  Hashsettest {  Public   Static   Void Main (string [] ARGs) {// same as above  }}  Class  Student {  Int  Num; string name; student (  Int  Num, string name ){  This . Num = Num;  This . Name = Name ;}  Public  String tostring (){ Return Num + "+" + name + "+" + This . Hashcode () + ";" ;}  Public   Int  Hashcode (){  Return Num * Name. hashcode ();}} 

Result:

 
False
False
1 + zhangsan +-1432604556; = bb
Data obtained through the key: ------- null
1 + zhangsan +-1432604556; = AA
Data obtained through the key: ------- null
2 + differentiation + 1362968; = cc
Data obtained through the key: ------- null

1 + zhangsan +-1432604556;
Null
1 + zhangsan +-1432604556;
Null
2 + differentiation + 1362968;
Null


4

Rewrite all:

Package  Collectionsframework;  Import  Java. util. hashmap;  Import  Java. util. hashset;  Import  Java. util. iterator;  Import  Java. util. Map;  Import  Java. util. Map. entry;  Public   Class  Hashsettest { Public   Static   Void  Main (string [] ARGs ){  //  Same as above  }}  Class  Student {  Int  Num; string name; student (  Int  Num, string name ){  This . Num = Num; This . Name = Name ;}  Public  String tostring (){  Return Num + "+" + name + "+" + This . Hashcode () + ";" ;}  Public   Boolean  Equals (Object OBJ ){  If ( Null = OBJ ){  Return  False  ;}  Else  {  If (OBJ Instanceof  Student) {student O = (Student) OBJ;  If ( This . Name = O. Name && This . Num = O. Num ){  Return   True ;}}  Return   False  ;}}  Public   Int  Hashcode (){  Return Num * Name. hashcode ();}} 

Result:

FalseTrue1 + zhangsan +-1432604556; =BB data obtained by key:-------Bb2 + discrimination + 1362968; =Data obtained by using the CC key:-------Bb1 + zhangsan +-1, 1432604556; Bb2 + differentiation + 1362968; Bb

 

From the second paragraphCodeAs you can see from the running results of, you only need to override equals for comparison,

HoweverNew Student (1, "zhangsan") are all stored in hashset (indicating that the object is not equal and the hashcode value is different), and in hashmap, M. get (new student (1, "zhangsan") returns NULL,

New student (1, "zhangsan ")Corresponds to two values: "AA", "BB", which is a conflict and cannot be used as a key value.

So at this time, we have to rewrite the hashcode at the same time, and then addOneThe same will overwrite the one previously added, so that only one is added. In hashmap, the two objects are the same, and the last one is used as the key value.

 

 

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.