The effective Java 3rd chapter is a common method for all objects

Source: Internet
Author: User

8th: Follow the general conventions when overriding equals

Overriding the Equals method may seem simple, but there are a number of overrides that can lead to errors and very serious consequences. The easiest way to avoid this type of problem is to not overwrite the Equals method, in which case each instance of the class is equal to itself.

So, when should we cover object.equals? If the class has its own unique "logical equality" concept (unlike the concept of object equivalence), and the superclass does not overwrite equals to achieve the desired behavior, then we need to overwrite
The Equals method. This usually belongs to the case of the value class. A value class is simply a class that represents a value, such as an integer or date. When programmers use the Equals method to compare references to value objects, they want to know whether they are logically equal, rather than whether they point to the same object.

The Equals method implements the equivalence relationship (equivalence relation):
· Reflexivity (reflexive). For any non-null reference value x, X.equals (x) must return True.
· 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.
· 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 also return true.
· Consistency (consistent). For any non-null reference value x and Y, as long as the information used by the comparison operation of equals in the object has not been modified, multiple calls to X.equals (Y) return true consistently, or return false consistently.
· For any non-null reference value x, x.equals (NULL) must return FALSE.

We cannot extend a class that can be instantiated while adding new value components while preserving the equals convention, unless you are willing to abandon the benefits of object-oriented abstraction.

While there is no satisfactory way to extend both the non-instantiated classes and the value components, there is a good workaround (workaround). As suggested in article 16th: Compounding takes precedence over inheritance.

Get the following tips for implementing the high-quality equals method

    1. Use the = = operator to check if the parameter is a reference to this object.
    2. Use the instanceof operator to check if the parameter is the correct type.
    3. Convert the parameters to the correct type. Because the instanceof test was done before the conversion, make sure it succeeds.
    4. For each key (significant) field in the class, check that the field in the parameter matches the corresponding field in the object.
      For a base type field that is neither float nor double, you can use the = = operator to compare, and for an object reference field, you can call the Equals method recursively, and for a float field, you can use the Float.compare method, or for a double field, The Double.compare is used. Special handling of float and double fields is necessary because of the existence of a float. NaN, -0.0f, and similar double constants; Refer to Float.equals's documentation for more information.
    5. Once you have written the Equals method, you should ask yourself three questions: whether it is symmetric, transitive, or consistent.

Warning about the Equals method:

    1. Always overwrite hashcode when you overwrite equals.
    2. Do not attempt to make the Equals method too intelligent.
    3. Do not replace object objects (parameters) in the equals declaration with other types.
9th: Overwrite equals when always overwrite Hashcode

Here is the agreed content, excerpted from the object specification [Java SE 6]

    1. During application execution, the Hashcode method must consistently return the same integer if the information used for the comparison of the object's Equals method has not been modified, and the same object is called multiple times. During multiple executions of the same application, the integer returned by each execution can be inconsistent.
    2. If two objects are equal according to the Equals (object) method, the Hashcode method that calls either object in both objects must produce the same integer result.
    3. If two objects are compared according to the Equals (object) method, they are not equal. Then calling the Hashcode method of any of these two objects does not necessarily produce a different integer result. However, programmers should know that it is possible to improve the performance of hash table by producing different integer results for unequal objects.

Note:
The HashMap has an optimization that caches the hash codes associated with each item, and does not have to verify the equivalence of the objects if the hash code does not match.

In the calculation of the hash code, the redundant domain (redundant field) can be excluded. In other words, if a field's value can be calculated from the other domain values participating in the calculation, you can exclude such a domain. You must exclude any fields that are not used in the equals comparison calculation. Otherwise it is likely to violate the second clause of the Hashcode Convention.

If a class is immutable and the cost of calculating the hash code is large, consider caching the hash code inside the object instead of recalculating the hash code every time the request is made. If you think most of this type of object will be used as a hash key (hash keys), you should calculate the hash code when you create the instance. Otherwise, you can select the lazy initialization (lazily initialize) hash code until hashcode is initialized the first time it is called (see 71st).

10th: Always overwrite ToString

If you specify the format of a string, then provide a matching static factory or constructor so that programmers can easily convert between the object and its string notation. Many value classes in the Java Platform Class Library Take this approach, including BigInteger, BigDecimal, and most of the basic type wrapper classes (Boxed primitive Class).

Whether or not you decide to specify a format, you should explicitly indicate your intentions in the document. If you want to specify a format, you should do so strictly.

11th: Carefully overwrite clone

The purpose of the Cloneable interface is to act as an mixin (Mixin interface) of an object (see 18th), indicating that such an object allows cloning (clone). Unfortunately, it did not succeed in achieving this goal. The main drawback is that it lacks a clone method, and the Clone method of object is protected. If you do not use the reflection (see 53rd), you cannot invoke the Clone method just because an object implements Cloneable. Even reflection calls can fail because there is no guarantee that the object must have an accessible clone method.

Since cloneable does not contain any method, what does it do? It determines the behavior of the protected Clone method in object: If a class implements Cloneable, the Clone method of object returns a domain-by-copy of the object , or the clonenotsupportedexcepion exception will be thrown. This is an extremely atypical usage of the interface and is not worth emulating. Typically, an interface is implemented to indicate what a class can do for its customers. However, for the Cloneable interface, it alters the behavior of the protected methods in the superclass.

If you extend a class that implements the Cloneable interface, you have no choice but to implement a well-behaved clone method. Otherwise, it is best to provide some other means of replacing the object copy, or simply not providing such a function. For example, for an immutable class, it doesn't make much sense to support the object copy because the copied object is not materially different from the original object.

Another good way to implement a copy is to provide a copy constructor (copy constructor) or copy factory (copy factory). The copy constructor is simply a constructor whose only parameter type is the class that contains the constructor, for example:

Some expert programmers simply never overwrite the Clone method and never call it unless the array is copied. You must be clear that for a class designed specifically for inheritance, if you fail to provide a well-behaved protected (protected) Clone method, its subclasses will not be able to implement the Cloneable interface.

12th: Consider implementing the comparable interface

If you are writing a value class that has a very obvious intrinsic sort relationship, such as alphabetical order, numerical order, or chronological order, you should strongly consider implementing this interface:

Compares this object to the specified object. Returns a negative integer, 0, or a positive integer when the object is less than, equal to, or greater than the specified object. Throws a ClassCastException exception if the object cannot be compared because of the type of the specified object.

The effective Java 3rd chapter is a common method 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.