【发布时间】:2014-11-06 18:31:28
【问题描述】:
假设,我有一个班级,叫它学生。学生类有一个元素,一个称为 Id 的 int。我想重写equals,这样如果将Student与Integer进行比较,该方法将返回true。喜欢:
public class OverrideTest {
public static void main(String[] args) {
Student a = new Student();
a.setId(5);
System.out.println(a.equals(5));
}
public static class Student {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (o instanceof Student) {
Student a = (Student) o;
if (a.getId() == this.getId())
return true;
}
if (o == this)
return true;
if (o instanceof Integer) {
int id = (Integer) o;
if (id == this.getId())
return true;
}
return false;
}
}
}
有没有办法向 IDE 发出信号表明一切正常且无需发送警告?
这将返回 true,但在 IDE 中会出现语法警告。
【问题讨论】:
-
我没有看到任何警告..
-
我建议您阅读 this question 并寻找在覆盖 equals 时需要注意的事项。
-
例如,如果你使用 boolean equals = student.equals(5),就会出现警告。
-
该警告很可能来自您的 IDE,而不是 JVM 本身。
-
不过,这不可以。它违反了
equals的合约,其中包括对称性(a.equals(b) == b.equals(a))。您无法让Integer.equals同意您的定义,因此您的定义将被破坏。