//重写了equals()而没有重写hashCode()方法
package Demo.collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.HashSet;
public class Foo {
int value;
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 int hashCode() {
return this.value;
}
*/
public static void main(String... args) {
ArrayList list = new ArrayList();
HashSet set = new HashSet();
Foo f1 = new Foo(1);
Foo f2 = new Foo(1);
list.add(f1);
set.add(f2);
Foo f3 = new Foo(1);
Foo f4 = new Foo(1);
System.out.println(list.contains(f3) + "," + set.contains(f4));
}
}
运行结果:true false
打开注释:true true
|