我制作了一些代码并发现对象ar eno等于 - 这是一个微不足道的问题,但不明白默认等于如何工作。
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
?
答案 0 :(得分:4)
您的课程目前只扩展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。
答案 1 :(得分:4)
如果不对对象重写equals(),则表示您正在比较两个不同的内存引用。因此,重写equals()来比较id字段。
答案 2 :(得分:1)
默认情况下会覆盖Object
的{{1}}方法,它会检查“相同的对象”而不是“相同的内容”。如果您想拥有equals
,则应覆盖它:
a.equals(b) == true
----- EDITED -----
答案 3 :(得分:0)
你应该为你的代码重写一个equals()方法,就像你的toString()方法一样。