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