.Contains()方法不调用重写的equals方法 [英] .Contains() method not calling Overridden equals method
问题描述
我遇到的问题是我创建了一个Foo对象的ArrayList,我重写了equals方法,而且我无法获得contains方法来调用equals方法。我已经尝试重写equals和hashcode,但它仍然无法正常工作。我敢肯定有一个合乎逻辑的解释,为什么这是,但我现在无法弄清楚我自己大声笑。我想要一种方法来查看列表是否包含指定的ID。
I am having an issue where I make an ArrayList of Foo objects, I override the equals method, and I cannot get the contains method to call the equals method. I have tried overriding equals and hashcode together, but it still doesn't work. I'm sure there is a logical explanation to why this is, but I cannot figure it out at the moment on my own lol. I just want a way to see if the list contains the specified id.
以下是一些代码:
import java.util.ArrayList;
import java.util.List;
public class Foo {
private String id;
public static void main(String... args){
Foo a = new Foo("ID1");
Foo b = new Foo("ID2");
Foo c = new Foo("ID3");
List<Foo> fooList = new ArrayList<Foo>();
fooList.add(a);
fooList.add(b);
fooList.add(c);
System.out.println(fooList.contains("ID1"));
System.out.println(fooList.contains("ID2"));
System.out.println(fooList.contains("ID5"));
}
public Foo(String id){
this.id = id;
}
@Override
public boolean equals(Object o){
if(o instanceof String){
String toCompare = (String) o;
return id.equals(toCompare);
}
return false;
}
@Override
public int hashCode(){
return 1;
}
}
输出:
false
false
false
OUTPUT: false false false
推荐答案
这是因为你的等于()
不是对称:
new Foo("ID1").equals("ID1");
但是
"ID1".equals(new Foo("ID1"));
不是真的。这违反了 equals()
合约:
is not true. This violates the equals()
contract:
equals方法实现等价关系非空对象引用:
The equals method implements an equivalence relation on non-null object references:
-
[...]
[...]
对称:对于任何非空引用值 x
和 y
, x.equals(y)
当且仅当 y.equals(x)
返回<时才返回true code> true 。
It is symmetric: for any non-null reference values x
and y
, x.equals(y)
should return true if and only if y.equals(x)
returns true
.
It不是的自反强>或者:
- 是自反:对于任何非空引用值
x
,x.equals(x)
应返回true。
- It is reflexive: for any non-null reference value
x
,x.equals(x)
should return true.
Foo foo = new Foo("ID1");
foo.equals(foo) //false!
@mbockus 提供正确的等于( )
:
public boolean equals(Object o){
if(o instanceof Foo){
Foo toCompare = (Foo) o;
return this.id.equals(toCompare.id);
}
return false;
}
但现在你必须传递 Foo的实例
到包含()
:
System.out.println(fooList.contains(new Foo("ID1")));
System.out.println(fooList.contains(new Foo("ID2")));
System.out.println(fooList.contains(new Foo("ID5")));
最后你应该实现 hashCode()
到提供一致的结果(如果两个对象相等,它们必须具有相等的 hashCode()
):
Finally you should implement hashCode()
to provide consistent results (if two objects are equal, they must have equal hashCode()
):
@Override
public int hashCode() {
return id.hashCode();
}
这篇关于.Contains()方法不调用重写的equals方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!