我在继续我的代码时遇到了一些麻烦,我会给你一个简单的例子(虽然它会更复杂一些,但这个简单的代码也不能正常工作)。
class Sign {
private String char;
private Integer freq;
public Sign(String c) {
this.char = c;
}
@Override
public boolean equals(Object o) {
String check = (String)o;
return check.equals(this.char);
}
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + this.char.hashCode();
return hash;
}
}
为了简单起见,我假设在 equals 方法中总是会有一个字符串。还有一些 hashCode() 也可以确保 contains() 方法可以工作,这里是测试本身:
ArrayList<Sign> queueOfSigns = new ArrayList<>();
Sign test = new Sign("C");
String c = "C";
queueOfSigns.add(test);
if(queueOfSigns.contains("C"))
System.out.println("I am here!");
无论如何,这个简单的测试代码在那种情况下总是返回 false - 所以“我在这里”消息永远不会出现。我一直在尝试一些不同的方法来处理我的代码,但这是因为这样做的想法是从字符串文本中获取单个字符并检查单个字符是否已经存在于 ArrayList 中。尽管如此 - 如果这个简单的测试无法正常工作,我无法继续,所以我想问你 - 我错过了什么。这是我第一次真正使用 equals() 和 hashCode() 方法让我自己的对象与 contains() 方法一起正常工作。
最佳答案
你的 equals
实现不正确。 equals
有一个特定的契约;该代码试图违反该契约(Contract)。来自文档:
The equals method implements an equivalence relation on non-null object references:
- It is reflexive: for any non-
null
reference valuex
,x.equals(x)
should returntrue
.- It is symmetric: for any non-
null
reference valuesx
andy
,x.equals(y)
should returntrue
if and only ify.equals(x)
returnstrue
.- It is transitive: for any non-
null
reference valuesx
,y
, andz
, ifx.equals(y)
returnstrue
andy.equals(z)
returnstrue
, thenx.equals(z)
should returntrue
.- It is consistent: for any non-
null
reference valuesx
andy
, multiple invocations ofx.equals(y)
consistently returntrue
or consistently returnfalse
, provided no information used inequals
comparisons on the objects is modified.- For any non-
null
reference valuex
,x.equals(null)
should returnfalse
.
无法将您的 Sign
类 equals
的实例生成为字符串。
关于java - ArrayList 的 contains() 方法总是返回带有自定义对象的 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52317618/