我编写了一些代码,发现对象是 eno equals - 这是一个微不足道的问题,但我不明白默认 equals 是如何工作的。
class A {
String id;
public A(String id) {
this.id = id;
}
public static void main(String args[])
{
A a = new A("1");
A b = new A("1");
System.out.println(a.id);
System.out.println(b.id);
System.out.println(a.equals(b));
}
}
结果是:
1
1
false
但我想要 a.equals(b) == true
为什么是 false
?
最佳答案
你的类目前只扩展了 Object
类,并且在 Object 类中 equals
方法看起来像这样
public boolean equals(Object obj) {
return (this == obj);
}
你需要的是覆盖这个方法,比如这样
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
A other = (A) obj;
if (id == other.id)
return true;
if (id == null)
return false;
if (other.id == null)
return false;
if (!this.id.equals(other.id))
return false;
return true;
}
此外,当您覆盖 equals
时,您可能应该覆盖 hashCode
方法,但这不是您的问题的主题。您可以阅读更多相关信息 here .
关于java - 为什么这两个 Java 对象不相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14824113/