ArrayList 的自定义 Contains 方法 [英] ArrayList's custom Contains method
问题描述
我有对象
class A {
private Long id;
private String name;
public boolean equals(Long v) {
return this.id.equals(v);
}
}
和这些对象的 ArrayList.我想要的是能够通过对象的字段检查该列表是否包含某个对象.例如:
and ArrayList of these objects. What I want is to be able to check if that list contains some object by object's field. For example:
ArrayList<A> list = new ArrayList<A>(); if (list.contains(0L)) {...}
但是重写的 Equals 方法对我没有帮助.我做错了什么?谢谢
but overrided Equals method is not helps me. What I am doing wrong? Thank you
更新我也应该覆盖 hashcode() 方法吗?
UPDATE And should I override a hashcode() method too?
推荐答案
这里有一些代码可以演示它是如何工作的:
here's some code that might demonstrate how it works out:
import java.util.ArrayList;
class A {
private Long id;
private String name;
A(Long id){
this.id = id;
}
@Override
public boolean equals(Object v) {
boolean retVal = false;
if (v instanceof A){
A ptr = (A) v;
retVal = ptr.id.longValue() == this.id;
}
return retVal;
}
@Override
public int hashCode() {
int hash = 7;
hash = 17 * hash + (this.id != null ? this.id.hashCode() : 0);
return hash;
}
}
public class ArrayList_recap {
public static void main(String[] args) {
ArrayList<A> list = new ArrayList<A>();
list.add(new A(0L));
list.add(new A(1L));
if (list.contains(new A(0L)))
{
System.out.println("Equal");
}
else
{
System.out.println("Nah.");
}
}
}
首先,有一个equals(Object o) 方法的覆盖.然后还有 hashCode() 的覆盖.另请注意,检查 equals 中的 instanceof A 将确保您不会尝试比较不同的对象.
First, there is an override of the equals(Object o) method. Then there is the override of the hashCode() as well. Also note that the instanceof A check in the equals will ensure that you're not trying to compare different objects.
这应该可以解决问题!希望有帮助!干杯:)
That should do the trick! Hope it helped! Cheers :)
这篇关于ArrayList 的自定义 Contains 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!