gpt4 book ai didi

java - 覆盖等于 : Telling IDE its okay to have different values?

转载 作者:行者123 更新时间:2023-12-01 17:02:30 26 4
gpt4 key购买 nike

假设我有一个类(class),称之为学生。学生类有一个元素,一个名为 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 中会出现语法警告。

最佳答案

正如 Yshavit 指出的,虽然您可以做您想做的事情,但这是极其危险的,因为它破坏了 .equals(...) 的对称性关系。例如,考虑:

Student s = new Student(5);
Integer i = new Integer(5);
if(s.equals(i)) System.out.println("s equals i");
else System.out.println("s doesnt equal i");
if(i.equals(s)) System.out.println("i equals s");
else System.out.println("i doesnt equal s");

输出:

s equals i
i doesnt equal s

从逻辑上讲,这没有任何意义。可能有一种方法可以说服您的 IDE 忽略此处的警告,但您几乎肯定应该注意它,并且不要让学生能够等于整数。

equals(..) 方法在 HashSets 等容器内部使用,因此该方法会导致内置结构出现不稳定的行为。

More about overriding equals(...)

关于java - 覆盖等于 : Telling IDE its okay to have different values?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26786806/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com