【发布时间】:2026-02-15 08:15:01
【问题描述】:
我有一个 ArrayList 的 Test 对象,它们使用字符串作为等效检查。我希望能够使用List.contains() 来检查列表是否包含使用某个字符串的对象。
简单地说:
Test a = new Test("a");
a.equals("a"); // True
List<Test> test = new ArrayList<Test>();
test.add(a);
test.contains("a"); // False!
等于和哈希函数:
@Override
public boolean equals(Object o) {
if (o == null) return false;
if (o == this) return true;
if (!(o instanceof Test)) {
return (o instanceof String) && (name.equals(o));
}
Test t = (Test)o;
return name.equals(t.GetName());
}
@Override
public int hashCode() {
return name.hashCode();
}
我读到了确保contains 适用于自定义类,它需要覆盖equals。因此,我很奇怪equals 返回 true,而 contains 返回 false。
我怎样才能做到这一点?
【问题讨论】:
-
一个类只能用同一个类测试
equals。 -
您对
equals的作用的想法是错误的,您应该将Test与Test的另一个实例进行比较 -
只有反过来才行,因为
"a".equals(new Test("a")) == false -
另外,
"a".equals(new Test("a")) != new Test("a").equals("a")是个问题。 -
@bayou.io
Object.equals的合约默认需要它,因为非空equality 的交换属性。