Effective java-Reading notes-Chapter III methods that are common to all objects

Source: Internet
Author: User
Tags comparable

Personal blog Sync release: Effective java-Reading notes-Chapter III methods that are common to all objects

Chapter III methods that are common to all objects

All non-final methods (equals, Hashcode, toString, clone, Finalize) have explicit general conventions because they are designed to be overwritten, if not adhered to, a hash-based collection (HashMap, HashSet, HashTable) may not work together with this class.

8th, please observe the general conventions when overriding equals

Override the Equals specification:

    1. Reflexivity (reflexive). For any non-null reference value X,x.equals (x) must return True.
    2. Symmetry (symmetric). For any non-null reference value x and Y, x.equals (y) must return true if and only if Y.equals (x) returns True.
    3. transitivity (transitive). For any non-null reference value x, Y, and Z, if X.equals (y) returns True, and Y.equals (Z) also returns True, then X.equals (z) must return true.
    4. Consistency (consistent). For any non-null reference value x and Y, only the information used by the equals comparison operation in the object has not been modified, and multiple calls to X.equals (Y) will return TRUE or false consistently.

Implement the Equals method:

    1. Use the = = operator to check if the parameter is a reference to this object. If yes, returns TRUE.
    2. Use the instanceof operator to check if the parameter is the correct type. False if not returned.
    3. Convert the parameters to the correct type. Before conversion, use instanceof to make sure it is correct.
    4. For each key field in the class, check to see if the field in the parameter matches the corresponding field in the object. Returns true if these test checks succeed, otherwise false is returned.
    5. When you have finished writing the Equals method, write the unit test to verify that it is symmetric, transitive, and consistent.

Attention:

    1. The Hashcode method is always overwritten when overriding the Equals method.
    2. Do not attempt to make the Equals method too intelligent. For example, file should not be treated as an equal to the document link.
    3. Do not replace object objects in the Equals method declaration with other types.
9th overwrite equals always overwrite hashcode

The Hashcode method returns the hash code value of the object. 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.

Hashcode General Agreement

    1. During application execution, as long as the information used in the comparison operation of the object's Equals method has not been modified, the Hashcode method must return the same integer consistently for the same object multiple calls. The integer does not need to be consistent from one execution of an application to another execution of the same application.
    2. If two objects are equal according to the Equals (object) method, then the Hashcode method must produce the same integer result on any object in the two object call.
    3. If two objects are not equal according to the Equals (object) method, then calling the Hashcode method on any of the two objects does not necessarily produce a different integer result. However, programmers should know that generating different integer results for unequal objects can improve the performance of the hash table.

For two objects equal to Equals (), their hashcode () must return a value equal

Overriding the Hashcode method

    1. The object hash code of equal equals is guaranteed to be equal to
    2. for equals different objects should try to do different hash code
      [1] a certain non-0 constant value (the general prime number), such as 17, stored in the int variable result;
      [2 "for each key field F in the object (refers to each domain considered in the Equals method):
      [2.1]boolean type, calculated (F 0:1);
      [2.2]byte, char, short, int, calculated (int) F;
      [2.3]long type, calculated (int) (f ^ (f>>>32));
      [2.4]float type, calculated float.floattointbits (afloat);
      [2.5]double type, calculate double.doubletolongbits (adouble) Get a long, then execute [2.3];
      [2.6] object reference, recursive invocation of its Hashcode method;
      [2.7] array field, calling its Hashcode method on each of these elements.
      [3] Save the above computed hash code to the int variable C, and then execute Result=37result+c;
      result+c; For example:
123456
 Public int hashcode () {    int;    *result+age;    result=*result+name.hashcode ();    return result;}
10th always overwrite ToString

The ToString General Convention indicates that the returned string should be concise, but informative, and easy to read expressions. A good tostring method can be used to make the class more comfortable, and when the object is passed to println, PRINGTF, String union Operation +, and log printing, ToString is automatically called.

It is recommended that all subclasses overwrite the ToString method.

11th, carefully overwrite clone

The Cloneable interface indicates that such an object allows cloning, it does not contain any methods, it alters the behavior of the protected method clone in the superclass, and if a class implements the Cloneable interface, object's Clone method returns a layer-by-level copy of the object. Otherwise, a Clonenotsupportexception exception will be thrown.

Overriding the Clone method is very careful, if the class contains complex data types, to deep copy, if the class has a final attribute, you cannot clone, because the final property in clone can no longer be assigned to the value.

We recommend that objects do not use the Clone method and use a static copy factory or copy constructor instead of the Clone method

12
 Public OBJ (obj obj);  Public Static newinstance (obj obj);
12th. Consider implementing the comparable interface

The comparable interface indicates that its instance has an intrinsic sort relationship.

Comparable statement:

    1. If the first object is less than the second object, the second object must be greater than the first object, and if the first object is equal to the second object, the second object must be equal to the first object, or the second object must be smaller than the first object if the first object is larger than the second object.
    2. If the first object is larger than the second object, and the second object is larger than the third object, then the first object must be greater than the third object.
    3. All objects that are considered equal at the time of comparison will certainly produce the same result when compared to other objects.

Comparable's declaration is similar to the declaration of equals, and also adheres to reflexivity, symmetry, and transitivity.

It is strongly recommended ((X.compareto (y) ==0) = = (X.eauals (y)), but this is not absolutely necessary.

Comparable implementation

The comparison of the fields in the CompareTo method is compared with the order of the comparisons, rather than the equivalence. The Note object reference domain can be implemented recursively by invoking the CompareTo method. If a domain does not implement the comparable interface, or if you need a nonstandard sort relationship, you can use a display comparator interface instead.

12345678910 
public  int  " Span class= "title" style= "" >compareto  (PhoneNumber pn) {int  Areacodedi        FF = Areacode-pn.areacode; if             (Areacodediff! = 0 )        return  Areacodediff;        int  Prefixdiff = Prefix-pn.prefix; if             (Prefixdiff! = 0 )        return  Prefixdiff;        //may occur beyond the int maximum exception     return  Linenumber-pn.linenumber; }


Personal blog Sync release: Effective java-Reading notes-Chapter III methods that are common to all objects


Effective java-Reading notes-Chapter III methods that are common to all objects

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.