Java Overwrite Equals method

Source: Internet
Author: User

when to rewrite equals ()

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

The object specification specifies that if you want to override Equals (), you also override the Hashcode ()

How to Overwrite equals ()Overwrite Equals method

1 Use the instanceof operator to check if the argument is the correct type.

2 for each "critical field" in the class, check the field values in the arguments to the corresponding fields in the current object.

3. For primitive type fields of non-float and double types, use = = to compare;

4 for the object reference domain, recursively calls the Equals method;

5 for float fields, use float. floattointbits (afloat) converted to int, then use = = comparison;

6 for double fields, use double. doubletolongbits (adouble) converted to int, then use = = comparison;

7 for array fields, call the Arrays.equals method.

Example:

    /*** * * * * java Eight basic data types*/    Private intA_int; Private  ShortA_short; Private CharA_char; Private byteA_byte; Private Doublea_double; Private floata_float; Private BooleanA_boolean; Private LongA_long; PrivateDemo demo;//Object    Private int[] intarray;//Array Fields    PrivateDemo[] Demos;//Object Array Field@Override Public Booleanequals (Object obj) {if(! (objinstanceofMydemo)) {            return false; } Mydemo Demo=(Mydemo) obj; returnDemo. a_int==a_int&&Demo. A_byte==a_byte&&Demo. A_boolean==a_boolean&&Demo. A_short==a_short&&Demo. A_char==a_char&&Demo. A_long==a_long&&Float.floattorawintbits (Demo. A_float)==float.floattorawintbits (a_float) &&Double.doubletorawlongbits (Demo. a_double)==double.doubletorawlongbits (a_double) &&Demo.demo.equals (Demo)&& This. Intsequals (Demo.intarray) && This. Objarrayequals (Demo.demos); }        Private BooleanIntsequals (int[] ints) {        returnarrays.equals (Intarray, ints); }    Private Booleanobjarrayequals (demo[] demos) {returnArrays.equals (demos, demos); }    

Java Overwrite Equals 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.