假设我有一个 Employee 类:
class Employee{
int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
class Example {
public static void main(String[] args){
Employee e1=new Employee();
Employee e2=new Employee();
e1.setId(1);
e2.setId(1);
System.out.println(e2.equals(e1));
}
}
为什么它给出错误? 这是什么原因,需要简单解释一下.equals和==方法。
最佳答案
- 所有类都继承自
Object
- 因此,它们会使用
Object.equals
方法,直到您覆盖它 Object.equals
测试引用相等性,它对类中的字段一无所知,并且无法测试“值”相等性
即要测试值是否相等,您需要覆盖 equals 并提供您自己的实现。举个例子:
class Employee{
int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
//see comments below for this next line
if (o.getClass() != this.getClass()) return false;
Employee other = (Employee)o;
return other.id == this.id;
}
}
您的覆盖应该 satisfy the rules自反性、对称性、传递性、一致性,并且对于 null
参数为 false
,因此上面的例子很复杂。为此,它执行以下操作:
- 背景调查(以提高效率)
- 空检查
instanceof
或getClass
检查(这两者之间的选择取决于您对子类型相等性的定义)- 强制转换为相同类型
- 最后,检查值字段
另请注意,覆盖等于 means you should also override hashCode :
@Override public int hashCode()
{
return id;
}
关于java - .equals 方法的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28001398/