Home Java javaTutorial Overriding of equals() method

Overriding of equals() method

Dec 16, 2016 am 10:38 AM
equals

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!


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles