请问各位大牛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
浮云间
相关分类