JDK-7014079 : java.util.HashSet's contains() does not honor java.util.Collection interface
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 6u23
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: windows_7
  • CPU: x86
  • Submitted: 2011-01-22
  • Updated: 2021-03-03
  • Resolved: 2011-04-05
Related Reports
Duplicate :  
Description
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.