请问各位大牛list和set调用contains方法时是比较两个元素的地址,还是调用他们的equals方法呢?public class Foo { int value; public Foo(int value) { this.value = value; } public boolean equals(Object obj) { if (obj instanceof Foo) { Foo foo = (Foo) obj; return value == foo.value; } else { return false; } } public static void main(String[] args) { //运行下面程序段: ArrayList list = new ArrayList(); HashSet set = new HashSet(); list.add(new Foo(1)); set.add(new Foo(1)); System.out.println(list.contains(new Foo(1)) + ","+ set.contains(new Foo(1))); //或者 System.out.println(new Foo(1).equals (new Foo(1)) + ","+ set.contains(new Foo(1))); }}我想问的就是为什么这个输出的结果是true,false
3 回答
浮云间
TA贡献1829条经验 获得超4个赞
public boolean contains(Object o) {
Iterator<E> it = iterator();
if (o==null) {
while (it.hasNext())
if (it.next()==null)
return true;
} else {
while (it.hasNext())
if (o.equals(it.next()))
return true;
}
return false;
}
这个是AbstractCollection的实现, AbstractList, AbstractSet都是以此为父类实现的.
添加回答
举报
0/150
提交
取消