在Java中实现equals方法时应遵循的指南?


为了比较两个对象,Object类提供了一个名为equals()的方法,此方法接受一个对象并将其与当前对象进行比较。

如果这两个对象的引用相等,则返回true;否则,此方法返回false。

但是,此方法只有在两个引用都指向同一个对象时才返回true。实际上,如果两个对象的內容相等,它应该返回true。

示例

class Employee {
   private String name;
   private int age;
   Employee(String name, int age){
      this.name = name;
      this.age = age;
   }
}
public class EqualsExample {
   public static void main(String[] args) {
      Employee emp1 = new Employee("Jhon", 19);
      Employee emp2 = new Employee("Jhon", 19);
      //Comparing the two objects
      boolean bool = emp1.equals(emp2);
      System.out.println(bool);
      Employee emp3 = emp1;
      boolean bool2 = emp1.equals(emp3);
      System.out.println(bool2);
   }
}

输出

false
true

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

重写equals()方法

为了解决这个问题,您可以重写equals()方法并比较两个对象,但是,在Java中,要使两个对象相等,它们必须处于等价关系中,这意味着equals方法应该检查三个条件:

  • 自反性 - a=a;

    使用此方法将对象与其自身进行比较时,结果应为true。

  • 对称性 - 如果a=b,则b=a;

    obj1.equals(obj2)的值应等于obj2.equals(obj1)。即,如果obj1.equals(obj2)返回true,则obj2.equals(obj1)必须返回true。

  • 传递性 - 如果a=b,b=c,则a=c;;

    如果obj1.equals(obj2)和obj2.equals(obj3)的值为true,则obj1.equals(obj3)的值必须为true。

在equals中将对象与当前对象进行比较时,需要检查以下条件。

  • 给定的对象不应为null。
if(obj == null ){
   return false;
}
  • 给定的对象应该是当前类的对象。
if(this.getClass() != obj.getClass()){
   return false;
}
  • 给定的对象应该等于当前对象。
if(this == obj){
   return true;
}
  • 当前对象的实例变量应该等于给定对象的实例变量。
Employee emp = (Employee)obj;
if(this.name != emp.name|this.age != emp.age){
   return false;
}

示例

如果您在equal方法中重写上面的示例,包括上面指定的条件,那么它将检查给定的对象是否等于当前的employee对象。

class Employee {
   private String name;
   private int age;
   Employee(String name, int age){
      this.name = name;
      this.age = age;
   }
   public boolean equals(Object obj) {
      if(obj == null ){
         return false;
      }
      if(this.getClass() != obj.getClass()){
         return false;
      }
      if(this == obj){
         return true;
      }
      Employee emp = (Employee)obj;
      if(this.name != emp.name||this.age != emp.age){
         return false;
      }
      return true;
   }
}
public class EqualsExample {
   public static void main(String[] args) {
      Employee emp1 = new Employee("Jhon", 19);
      Employee emp2 = new Employee("Jhon", 19);
      //Comparing the two objects
      boolean bool = emp1.equals(emp2);
      System.out.println(bool);
      Employee emp3 = emp1;
      boolean bool2 = emp1.equals(emp3);
      System.out.println(bool2);
   }
}

输出

true
true

更新于:2020年7月2日

147 次浏览

启动您的职业生涯

完成课程获得认证

开始
广告