Home > Java > javaTutorial > body text

Overriding of equals() method

高洛峰
Release: 2016-12-16 10:38:07
Original
1370 people have browsed it

1. Why does the equals() method need to be rewritten?

Determine whether two objects are logically equal, such as judging whether instances of two classes are equal based on the member variables of the class. However, the equals method in inherited Object can only determine whether two reference variables are the same object. In this way we often need to override the equals() method.

When we add elements to a collection without duplicate objects, objects are often stored in the collection. We need to first determine whether there are known objects in the collection, so we must override the equals method.

2. How to rewrite the equals() method?

Requirements for overriding the equals method:
1. Reflexivity: x.equals(x) should return true for any non-null reference x.
2. Symmetry: For any reference to x and y, if x.equals(y) returns true, then y.equals(x) should also return true.
3. Transitivity: For any reference x, y and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should also return true.
4. Consistency: If the objects referenced by x and y have not changed, then calling x.equals(y) repeatedly should return the same result.
5. Non-nullability: For any non-null reference x, x.equals(null) should return false.

Format:


Java code

public boolean equals(Object obj) {  
    if(this == obj)  
        return false;  
    if(obj == null)  
        return false;  
    if(getClass() != obj.getClass() )  
        return false;  
    MyClass other = (MyClass)obj;  
    if(str1 == null) {  
         if(obj.str1 != null) {  
              return false;  
         }  
    }else if (!str1.equals(other.str1) )  
             return false;  
     }  
    if(var1 != other.var1)  
        return false;  
    return true;  
}
Copy after login

If new features are added to the subclass while retaining the equals method, it will be more complicated.


Next, let’s understand the above agreement through examples. We first start with a simple non-mutable two-dimensional point class:

public class Point{ 
  private final int x; 
  private final int y; 
  public Point(int x, int y){ 
    this.x = x; 
    this.y = y; 
  } 
  public boolean equals(Object o){ 
    if(!(o instanceof Point)) 
      return false; 
    Point p = (Point)o; 
      return p.x == x && p.y == y; 
  } 
}
Copy after login


Suppose you want to extend this class to add color information to a point:

public class ColorPoint extends Point{ 
  private Color color; 
  public ColorPoint(int x, int y, Color color){ 
    super(x, y); 
    this.color = color; 
  } 
  //override equasl() 
  public boolean equals(Object o){ 
    if(!(o instanceof ColorPoint)) 
     return false; 
    ColorPoint cp = (ColorPoint)o; 
    return super.equals(o) && cp.color==color; 
  } 
}
Copy after login


We override the equals method, only if It returns true only when the actual parameter is another colored point with the same position and color. But the problem with this method is that when you compare a normal point with a colored point, and vice versa, you may get different results:

public static void main(String[] args){ 
  Point p = new Point(1, 2); 
  ColorPoint cp = new ColorPoint(1, 2, Color.RED); 
  System.out.println(p.equals(cp)); 
  System.out.println(cp.eqauls(p)); 
}
Copy after login

Running results:
true
false
Such a result obviously violates To correct the symmetry, you can try this to correct this problem: let ColorPoint.equals ignore color information when performing "mixed comparisons":

public boolean equals(Object o){ 
  if(!(o instanceof Point)) 
    return false; 
  //如果o是一个普通点,就忽略颜色信息 
  if(!(o instanceof ColorPoint)) 
    return o.equals(this); 
  //如果o是一个有色点,就做完整的比较 
  ColorPoint cp = (ColorPoint)o; 
  return super.equals(o) && cp.color==color; 
}
Copy after login

What will be the result of this method? Let’s test it first:

public static void main(String[] args){ 
  ColorPoint p1 = new ColorPoint(1, 2, Color.RED); 
  Point p2 = new Point(1, 2); 
  ColorPoint p3 = new ColorPoint(1, 2, Color.BLUE); 
  System.out.println(p1.equals(p2)); 
  System.out.println(p2.equals(p1)); 
  System.out.println(p2.equals(p3)); 
  System.out.println(p1.eqauls(p3)); 
}
Copy after login

Running result:
true
true
true
false

This method does provide symmetry, but it sacrifices transitivity (by convention, p1.equals(p2) and p2.equauals(p3) all returns true, p1.equals(p3) should also return true). How to solve it?

In fact, this is a basic question about equivalence relations in object-oriented languages. There is no easy way to extend an instantiable class to add new features while retaining the equals convention. The new solution is to no longer let ColorPoint extend Point, but to add a private Point field and a public view method to ColorPoint:

public class ColorPoint{ 
  private Point point; 
  private Color color; 
  public ColorPoint(int x, int y, Color color){ 
    point = new Point(x, y); 
    this.color = color; 
  } 
  //返回一个与该有色点在同一位置上的普通Point对象 
  public Point asPoint(){ 
    return point; 
  } 
  public boolean equals(Object o){ 
    if(o == this) 
     return true; 
    if(!(o instanceof ColorPoint)) 
     return false; 
    ColorPoint cp = (ColorPoint)o; 
    return cp.point.equals(point)&& 
             cp.color.equals(color); 
  } 
}
Copy after login

Another solution is to design Point as An abstract class so that you can add new features to subclasses of the abstract class without violating the equals contract. Because abstract classes cannot create instances of the class, none of the problems mentioned above will occur.

Key points of overriding the equals method:
1. Use the == operator to check "whether the actual parameter is a reference to the object".

2. Determine whether the actual parameter is null
3. Use the instanceof operator to check "whether the actual parameter is of the correct type".
4. Convert the actual parameters to the correct type.
5. For each "key" field in this class, check whether the field in the actual parameter matches the corresponding field value in the current object.
 For fields of basic types that are neither float nor double, you can use the == operator for comparison; for fields of object reference types, you can call the equals method of the referenced object recursively; for fields of float type, First use Float.floatToIntBits to convert to an int type value, and then use the == operator to compare the int type value; for double type fields, first use Double.doubleToLongBits to convert to a long type value, and then use the == operator Compares values ​​of type long.
6. After you write the equals method, you should ask yourself three questions: Is it symmetric, transitive, and consistent? (The other two characteristics will usually be satisfied by themselves) If the answer is no, then please find the reason why these characteristics are not satisfied, and then modify the code of the equals method.






For more articles related to rewriting the equals() method, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template