Valid java-Reading Notes-Chapter 3 common methods for all objects

Source: Internet
Author: User

Valid java-Reading Notes-Chapter 3 common methods for all objects

 

Chapter 3 common methods for all objects

 

All non-final methods (equals, hashCode, toString, clone, and finalize) have clear general conventions because they are designed to be overwritten. If they are not followed, A hash-based set (HashMap, HashSet, and HashTable) may not work together with this class.

Article 3 When covering equals, follow the general conventions

Covering equals specifications:

  1. Reflexive ). For any non-null reference value x, x. equals (x) must return true.
  2. Symmetry ). For any non-null reference values x and y, if and only if y. equals (x) returns true, x. equals (y) must return true.
  3. Transmission ). For any non-null reference values 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. Consistent ). For any non-null reference values x and y, only the information used in the comparison operation of equals in the object is not modified, and x is called multiple times. equals (y) returns true or false in the same way.

    Implement the equals method:

    1. Use the = Operator to check whether the parameter is a reference to this object ". If yes, true is returned.
    2. Use the instanceof operator to check whether the parameter is of the correct type ". If not, false is returned.
    3. Converts a parameter to a correct type. Use instanceof to determine before conversion to ensure correctness.
    4. For each "key" field in the class, check whether the field in the parameter matches the corresponding field in the object. If these test checks are successful, true is returned; otherwise, false is returned.
    5. After the equals method is compiled, write a unit test to verify whether it is symmetric, transmitted, and consistent.

      Note:

      1. Override the hashCode method when overwriting the equals method.
      2. Do not try to make the equals method too intelligent. For example, File should not be treated as the same as File link.
      3. Do not replace the Object in the equals method declaration with another type. 9th hashCode overwrites equals

        The hashcode method returns the hash code value of this object. It is usually necessary to override the hashCode method to maintain the conventional protocol of the hashCode method, which declares that equal objects must have equal hash codes.

        Conventional hashCode Protocol

        1. During application execution, as long as the information used in the comparison operation of the equals method of the object is not modified, the same object is called multiple times, all hashCode methods must return the same integer. This integer does not need to be consistent from one execution of an application to another execution of the same application.
        2. If the two objects are equal according to the equals (Object) method, the hashCode Method on any of the two objects must produce the same integer result.
        3. If the comparison between the two objects based on the equals (Object) method is not equal, then calling the hashCode Method on any of the two objects does not necessarily produce different integer results. However, programmers should know that generating different integer results for unequal objects can improve the performance of the hash table.

          For two objects with equal equals (), the value returned by hashCode () must be equal.

          Override hashCode

          1. Ensure that the object hash codes of equals must be equal.
          2. Try to use different hash codes for different equals objects.
            The specific steps are as follows:
            [1] store a non-zero constant value (generally a prime number), for example, 17, in the result of the int variable;
            [2] for each key field f in an object (each field considered in the equals method ):
            [2.1] boolean type, computing (f? 0: 1 );
            [2.2] byte, char, short, int type, calculation (int) f;
            [2.3] long type, calculation (int) (f ^ (f >>> 32 ));
            [2.4] float type, computing Float. floatToIntBits (afloat );
            [2.5] double type, calculate Double. doubleToLongBits (adouble) to get a long value, and then execute [2.3];
            [2.6] references an object and recursively calls its hashCode method;
            [2.7] array field, which calls its hashCode method for each element.
            [3] Save the hash code calculated above to int variable c, and then execute result = 37 result + c;
            [4] Return result.
            In fact, the idea is: first take a base, and then convert each field considered in equals () into an integer, and then execute result = 37 result + c; for example:
            123456
            public int hashCode(){    int result = 17;    result = 31*result+age;    result=31*result+name.hashCode();    return result;}
            10th always overwrite toString

            ToString conventions indicate that the returned string should be a concise, informative, and easy-to-read expression. A good toString method can make the class more comfortable to use. When the object is passed to println, pringtf, string union operation +, and log printing, toString will be automatically called.

            We recommend that all subclasses overwrite the toString method.

            11th careful coverage of clone

            The Cloneable interface indicates that such an object can be cloned. It does not contain any methods. It changes the behavior of the protected method clone in the superclass. If a class implements the Cloneable interface, the clone method of the Object returns the layer-by-layer copy of the Object, otherwise the CloneNotSupportException exception will be thrown.

            Be very careful when overwriting the clone method. If the class contains complex data types, perform in-depth replication. If the class contains the final attribute, you cannot clone it, because the final attribute cannot be assigned a value during clone.

            We recommend that you replace the clone method with the static copy factory or copy constructor instead of the clone method for objects.

            12
            public Obj(Obj obj);public static Obj newInstance(Obj obj);
            Article 21 consider implementing the Comparable Interface

            The Comparable interface indicates that its instance has an internal sorting relationship.

            Comparable statement:

            1. If the first object is smaller than the second object, the second object must be greater than the first object. If the first object is equal to the second object, the second object must be equal to the first object; if the first object is greater than the second object, the second object must be smaller than the first object.
            2. If the first object is greater than the second object and the second object is greater than the third object, the first object must be greater than the third object.
            3. All objects considered equal during comparison will produce the same results when compared with other objects.

              The Comparable statement is similar to the equals statement. It also complies with self-inversion, symmetry, and transmission.

              Strongly recommended (x. compareTo (y) = 0) = (x. eauals (y), but this is not absolutely necessary.

              Comparable implementation

              The comparison of fields in the compareTo method is sequential, rather than the comparison of equality. The reference field of the Note object can be implemented by calling the compareTo method recursively. If a domain does not implement the Comparable interface, or you need a non-standard sorting relationship, you can use a displayed Comparator interface instead.

              12345678910
              Public int compareTo (PhoneNumber pn) {int areaCodeDiff = areaCode-pn. areaCode; if (areaCodeDiff! = 0) return areaCodeDiff; int prefixDiff = prefix-pn. prefix; if (prefixDiff! = 0) return prefixDiff; // The return lineNumber-pn. lineNumber exception may occur below the int maximum value ;}

               

              Simultaneous publishing of personal blogs: Proactive java-Reading Notes-Chapter 3 common methods for 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.