Override the Equals () method in Java while overriding the Hashcode () method

Source: Internet
Author: User

Case:

For example, a person at different times in the system generated two instances, to determine whether these two instances is a person, compare the ID number on it. Assuming these two instances, one is a file created at age 16, one is a 24-year-old file, and if you do not rewrite the Equals method, these two instances are definitely not a person.

What if the hashcode and equals are not rewritten (native)?

1. The hashcode value that is not overridden (native) is a value that is converted based on the memory address.

2. The Equals method that is not overridden (native) is a method that strictly determines whether an object is equal (Object1 = = object2).

Let's take a look at the general agreement of Object.hashcode (from page 45th of "effective Java")

    1. During an application execution, if the information used to compare the Equals method of an object is not modified, then the Hashcode method is called multiple times for that object, and it must consistently return the same integer. This integer can be different during multiple executions of the same application, that is, the integer returned by this application execution is inconsistent with the integer returned by the next execution.
    2. If two objects are equal according to the Equals (object) method, the Hashcode method that calls either object in both objects must produce the same integer result.
    3. If two objects are not equal according to the Equals (object) method, then calling the Hashcode method of either object in both objects does not require that a different integer result be produced. However, programmers should be aware of the fact that it is possible to increase the performance of a hash table by generating distinct integer results for unequal objects.

If only the Equals method is overridden and the Hashcode method is not overridden, the second clause of the Convention is violated: equal hashes must have equal hash codes (hashcode)
Also for HashSet and hashmap these hash-based values (hash) implementations of the class.

The public boolean equals (Object obj) in object objects, and the method returns true for any non-null reference value x and Y, when and only if X and Y refer to the same object;
Note: When this method is overridden, it is often necessary to override the Hashcode method to maintain the general contract of the Hashcode method, which declares that the equality object must have an equal hash code. As follows:
(1) when Obj1.equals (OBJ2) is true, obj1.hashcode () = = Obj2.hashcode () must be true
(2) when obj1.hashcode () = = Obj2.hashcode () is False, Obj1.equals (OBJ2) must be false

If you do not override Equals, then the comparison will be whether the object's reference points to the same memory address, which is overridden to compare the value of two objects for equality.

So if we rewrite the euqals for an object, it means that as long as the values of the member variables of the object are equal then Euqals equals true, but does not rewrite hashcode, then we are new to the object,
When the original object. Equals (New Object) equals True, the hashcode of the two is not the same, resulting in an inconsistent understanding, such as when storing a hash collection (such as set Class), will store two values of the same object,
Cause confusion, therefore, it is also necessary to rewrite hashcode ()
To illustrate:
 Packagecom.zcj.eg002;ImportJava.util.*; Public classHelloWorld { Public Static voidMain (string[] args) {Name N1=NewName ("zcj001"); Name N2=NewName ("zcj001"); Collection C=NewHashSet ();        C.add (N1); System.out.println ("------------");        C.add (N2); System.out.println ("------------");        System.out.println (N1.equals (N2)); System.out.println ("------------");        System.out.println (N1.hashcode ());        System.out.println (N2.hashcode ());    System.out.println (c); }}className {PrivateString ID;  PublicName (String id) { This. ID =ID; }         PublicString toString () {return  This. ID; }     Public Booleanequals (Object obj) {if(objinstanceofName) {Name Name=(Name) obj; System.out.println ("***equal***" +name.id); return(Id.equals (name.id)); }        return Super. Equals (obj); }             Public inthashcode () {name Name= (Name) This; System.out.println ("***hash***" +name.id); returnId.hashcode (); }}

When overriding Equals () and Hashcode () run the results as follows:

Equals is the same value as True,hashcode

When only overriding equals () does not rewrite the hashcode () operation results as follows:

Equals is a value of True,hashcode different from the second clause of the violation Convention

When only overriding hashcode () does not override the Equals () operation results are as follows:

Override the Equals () method in Java while overriding the Hashcode () method

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.