Why would Java rewrite the hashcode and equals methods?

Source: Internet
Author: User

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).

Why do I need to rewrite the Equals and Hashcode methods?
When judging objects in our business systems, it is sometimes necessary not to be equal in a strict sense, but as a business object. In this case, the native Equals method will not meet our needs.
So this time we need to rewrite the Equals method to meet the requirements on our business systems. So why do you need to rewrite the Hashcode method when overriding the Equals method?
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 underlying processing mechanism of HASHMAP is to store the data in the array (node<k,v>[] table), where the key is the processing of the array subscript. The subscript of an array is determined by the return value of the Hashcode method based on the passed-in element and the specific value.

If there is already a value placed on the array position, and the incoming key value is equal, then the value is not processed, if not equal, if the array position does not have an entry, it is inserted and added to the corresponding linked list. Checks whether the key exists and is determined by the hashcode value. So if you do not rewrite hashcode, it may lead to HashSet, HashMap can not operate normally,
If we save a custom object to HashMap or HashSet and its similar implementation class, if the property of the object participates in the evaluation of hashcode, then it is not possible to modify the property that the object parameter Hashcode computed. It is possible to remove elements that cause a memory leak.

Extended:
When overriding the Equals method, the following general conventions need to be adhered to:
1, the reflexive nature.
For any reference value x,x.equals (x) must be true.
2, symmetry.
For any reference value x and Y, x.equals (y) must also return true if and only if Y.equals (x) returns True.
3, transmission.
If X.equals (Y) returns true for any of the reference values X, Y, and Z, and Y.equals (Z) also returns True, then X.equals (z) must also return true.
4, consistency.
For arbitrary reference values x and Y, if the object used for the equals comparison is not modified, then X.equals (y) for this call either returns true consistently or returns false consistently.
5, for any non-null reference value x,x.equals (NULL) must return FALSE.
The approximate way to override the Hashcode method:
A, a non-0 constant value, such as 17 (preferably a prime number), is stored in a variable called the int type of result.
b, for each key field in the object F (the value Equals method is considered in each domain), complete some steps:
1. Calculate the hash of type int for this field C:
1), if the field is a Boolean type, the calculation (f? 0:1).
2), if the field is a byte, char, short, or int type, evaluates (int) F.
3), if the field is a float type, calculate float.floattointbits (f).
4), if the field is a long type, evaluates (int) (f ^ (f>>>32)).
5), if the field is a double type, calculate Double.doubletolongbits (f) to get a long value, and then follow step 4 to calculate the hash value for that long value.
6), if the domain is an object reference, and the Equals method of the class compares the domain recursively by calling equals, the same domain is recursively called hashcode. If a more complex comparison is required, a "canonical representation" is computed for the domain, and then a call to Hashcode is made for that paradigm. If the value of this field is NULL, 0 (or some other constant) is returned
7), if the field is an array, each element is treated as a separate domain. In other words, recursively apply the above rules, calculate a hash code for each important element, and then combine the hash values according to the procedure below.
2, according to the following formula, the calculated hash code C in step 1 is combined into the result:
result = 31*result+c.
C, return result.
D, after writing the Hashcode method, ask yourself "if the instances of equality have equal hash codes". If not, find out the cause and modify it.
you can easily override the Hashcode method by Org.apache.commons.lang.builder.HashCodeBuilder this tool class.

Why would Java rewrite the hashcode and equals methods?

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.