问题描述
假设我有这样的课程:
class A {
int elementA;
int elementB
}
我也有一个像这样的 ArrayList
:ArrayListlistObj
.
I also have an ArrayList
like this: ArrayList<A> listObj
.
如何仅使用 A
的某些属性来检查该列表是否包含对象?例如.只考虑 elementA
来查找对象 newA{elementA}
是否已经在列表中?
How can I check if that list contains an object using only some of the properties of A
? E.g. considering only elementA
for finding if object newA{elementA}
is already in the list?
对于对象A
,我定义了一个equals
方法,我只考虑了elementA
,但这还不够.
For object A
I have defined an equals
method, where I consider only the elementA
, however this is not enough.
推荐答案
List#contains() 方法使用 equals()
方法来评估两个对象是否相同.因此,您需要覆盖 A
类中的 equals()
并覆盖 hashCode()
.
List#contains() method uses the equals()
method to evaluate if two objects are the same. So, you need to override equals()
in your Class A
and also override the hashCode()
.
@Override
public boolean equals(Object object)
{
boolean isEqual= false;
if (object != null && object instanceof A)
{
isEqual = (this.elementA == ((A) object).elementA);
}
return isEqual;
}
@Override
public int hashCode() {
return this.elementA;
}
这篇关于检查 ArrayList 是否包含给定的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!