Effective Java reading notes-a common method for all objects

Source: Internet
Author: User

All classes in Java inherit from the object class, and there are a number of common methods in the object class that are discussed in this chapter: for common methods in the object class, our classes do not inherit, and the things to be aware of when inheriting.

1th: Equals (), please observe the General Convention when overwriting

First look at the situation where you do not need to overwrite:

1. Each instance of a class is inherently unique. (such as static, Singleton, etc.), so that you do not have to deliberately overwrite the Equals method, and the Equals () method of the object class is sufficient

2. Do not care whether the class implements the "logical equality" test function. We use equals to determine whether two objects are "logically equal", such as whether the value of a string class is equal. If this class does not require this functionality, then it is natural that we do not need to overwrite the Equals () method.

3. The superclass has overridden the Equals () method, and the behavior that inherits from the superclass is appropriate for the subclass.

4. There is a "value class" that does not need to be overwritten, that is, an instance-controlled class, to ensure that "there is only one object per value", the enumeration type is this class, for such classes, logical equality and object equality is one thing, so do not need to overwrite the Equals () method

So when do you need to overwrite it?

If the class has its own unique concept of "logical equality" and the parent does not overwrite equals to achieve the desired behavior , then we need to overwrite the Equals () method. This usually belongs to the " value class ". A value class is typically a class that represents only values, such as Integer, in which programmers only want to know if their values are equal and whether they point to the same object when compared with equals.

The Equals method needs to implement an " equivalence relationship " with four aspects:

1. Reflexivity. X.equals (x) must always return true.

2. Symmetry. If X.equals (y) is =true, then y.equals (x) must also be true.

3. transitivity. If there is x.equals (y) = True,y.equals (Z) = True, then there must be X.quals (z) = True.

4. Consistency. As long as the value is not modified, the value of multiple calls to X.equals (Y) should always be equal.

Here are some examples that violate these 4 articles.

Violation of reflexivity: This is generally very small, because this article only requires that the object equals itself. If it is violated, suppose you add an object to a collection, and then query, the contains method of the collection will tell you that the element does not exist in the collection.

Violation of symmetry: Consider the following class, which implements a case-sensitive string, but does not consider case when compared.

 Public Final classcaseinsensitivestring{Private FinalString S; ...     Public Booleanequals (Object o) {if(Oinstanceofcaseinsentivestring) {            returnS.equalsignorecase (((caseinsentivestring) O). s); if(OinstanceofString)//consider a comparison with the ordinary string class            returns.equalsignorecase (String) o); return false; }}    

It seems to be well thought out, and when compared, consider the case that the incoming object is this class and the String class. However, suppose we have two objects:
caseinsensitivestring cis = new caseintensitivestring ("Polish");

String s = "Polish";

Well, apparently cis.equals (s) =true. But here's the problem, s.equals (CIS) = False. This is a violation of symmetry.

The workaround is that if a comparison of Class B objects is introduced in the Equals method of Class A, then Class B will, in turn, introduce a comparison of Class A.

Violation of transitivity: The violation of this rule is generally due to the addition of a new value object when inheriting from the subclass. The information that is added by the subclass affects the comparison result of equals.

For example, we have a simple point class:

 Public classpoint{Private Final intx; Private Final inty;  PublicPoint (intXinty) {         This. x =x;  This. y =y; }     Public Booleanequals (Object o) {if(! (OinstanceofPoint )) return false; Point P=(point) O; return  This. x = = p.x && This. y = =p.y; }}

Suppose you want to extend this class and add a color message to each point:

 Public class extends point{    privatefinal  color color;      Public ColorPoint (int x,int  y, Color c) {        Super(x, y        ); = c;    }}

What does the Equals method do? There are two considerations: 1. Compare only with colored points, to return true if the X,y,color are equal, and for objects that are not colored points, the returned result is always False
2. Colored dots can also be compared with the normal point, if compared with the normal point, the value of x, Y is compared.

See the implementation of the first method:

 Public Boolean equals (Object o) {    if(!  (o instance of ColorPoint)) {        returnfalse;     return Super. Equalso) && ((ColorPoint) o). color = = color;    }}

If there is a colored dot object, CP (1,2,red) and a normal point object P (in), then p.equals (cp) = True,cp.equals (P) = False. Violates the symmetry.

The second method:

 Public Booleanequals (Object o) {if(! (OinstanceofPoint )) return false; if(! (Oinstanceofcolorpoint))//if the object is not a ColorPoint class, use the Equals method of the object to determine        returnO.equals ( This); return Super. Equalso) && ((ColorPoint) o). Color =color;}

This method achieves symmetry, but at the expense of transitivity. Consider colored dots CP1 (1,2,red), CP2 (1,2,blue) and normal point P (for
There is cp1.equals (p) = True, P.equals (CP2), but Cp1.equals (CP2). is a violation of transitivity.

We cannot expand a class that can be instantiated while adding a new value component and preserving the equals convention.

How to solve it?

Composition takes precedence over inheritance.

Instead of inheriting the point class, we create a new ColorPoint class that joins a reference to the point class.

I'll write this today and continue tomorrow.

Effective Java reading notes-a common method for all objects

Related Article

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.