Java: Overriding Equals () and Hashcode ()

Source: Internet
Author: User
Tags comparison hash

The following is summarized from "effective Java".

1. When to rewrite equals ()

When a class has its own unique concept of "logical equivalence" (different from the concept of object identity).

2. Design Equals ()

[1] Use the instanceof operator to check whether the argument is the correct type.

[2] For each "critical field" in a class, check the field in the argument for the corresponding field value in the current object.

[2.1] Use = = Comparison for primitive type fields of non-float and double types;

[2.2] recursively calls the Equals method for the object reference domain;

[2.3] For the float field, use Float.floattointbits (afloat) to convert to int, then use = = comparison;

[2.4] for double fields, convert to int using double.doubletolongbits (adouble), then use = = comparison;

[2.5] For array fields, invoke the Arrays.equals method.

3. When you rewrite equals (), always rewrite hashcode ()

Depending on the Equals method of a class (rewritten), two distinct instances may be logically equal, but, according to the Object.hashcode method, they are just two objects. Therefore, a violation of the "equal object must have an equal hash code".

4. Design Hashcode ()

[1] Store a non-0 constant value, such as 17, in the int variable result;

[2] For each of the key domain F in the object (the Equals method is considered in each field):

[2.1]boolean type, calculation (f. 0:1);

[2.2]byte,char,short type, calculation (int);

[2.3]long type, computed (int) (f ^ (f>>>32));

[2.4]float type, calculated float.floattointbits (afloat);

[2.5]double type, computed double.doubletolongbits (adouble) Gets a long, then executes [2.3];

[2.6] An object reference that recursively calls its Hashcode method;

[2.7] An array field that calls its Hashcode method on each of these elements.

[3] Save the computed hash code to int variable C and execute result=37*result+c;

[4] returns result.

Related Article

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.