Duplicate :
|
FULL PRODUCT VERSION : java version "1.6.0_23" Java(TM) SE Runtime Environment (build 1.6.0_23-b05) Java HotSpot(TM) Client VM (build 19.0-b09, mixed mode, sharing) ADDITIONAL OS VERSION INFORMATION : Microsoft Windows [Version 6.1.7600] A DESCRIPTION OF THE PROBLEM : java.util.HashSet's contains() does not use equals() to compare objects. It uses hashCode() instead. This differs from the specification of Collection interface. STEPS TO FOLLOW TO REPRODUCE THE PROBLEM : Define a new class A with one attribute, id. Override its equals() that return true if this.id==other.id Create a HashSet<A>. Add an instance of A with id=1 to the HashSet. Create another instance of A with id=1. Use the new instance as the argument of HashSet's contains() contains() returns false REPRODUCIBILITY : This bug can be reproduced always. ---------- BEGIN SOURCE ---------- import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; public class MyClass { /** * @param args */ public static void main(String[] args) { List<Dummy> dummyList = new LinkedList<MyClass.Dummy>(); MyClass a = new MyClass(); Dummy d1 = a.new Dummy(1); dummyList.add(d1); Set<Dummy> dummySet = new HashSet<Dummy>(); dummySet.add(d1); boolean result = dummySet.contains(a.new Dummy(1)); System.out.println(result); } class Dummy { int id; public Dummy(int id) { this.id = id; } @Override public boolean equals(Object obj) { if (! (obj instanceof Dummy)) { return false; } Dummy other = (Dummy) obj; return this.id == other.id; } } } ---------- END SOURCE ---------- CUSTOMER SUBMITTED WORKAROUND : Override hashCode() too.