JDK-4492195 : HashSet.contains() doesn`t work with null keys
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 1.4.0
  • Priority: P3
  • Status: Closed
  • Resolution: Duplicate
  • OS: solaris_2.6
  • CPU: sparc
  • Submitted: 2001-08-15
  • Updated: 2021-03-03
  • Resolved: 2001-08-16
Related Reports
Duplicate :  
Description

Name: auR10023			Date: 08/15/2001



java.util.HashSet.contains(Object ) doesn`t work with null objects. 
The javadoc for this method says nothing about the difference between  
null and non-null objects. 

javadoc for HashSet:

...
public boolean contains(Object o)

     Returns true if this set contains the specified element. 

     Specified by:
          contains in interface Set
     Overrides:
          contains in class AbstractCollection
     Parameters:
          o - element whose presence in this set is to be tested.
     Returns:
          true if this set contains the specified element.
...

But this method returns false for null object contained in the HashSet.

Here is the example:

---------------t.java---------------
import java.util.*;

class t {
    public static void main(String args[]) {
        HashSet set = new HashSet();

        set.add(null);
        set.add("dd");
        System.out.println("size of HashSet :" + set.size());
        System.out.println( set.contains(null));
    }
} 


#java -version
java -version
java version "1.4.0-beta_refresh"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-beta_refresh-b75)
Java HotSpot(TM) Client VM (build 1.4.0-beta_refresh-b75, mixed mode)

#java -cp . t
size of HashSet :2
false

#java -version 
java version "1.3.0"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.0-C)
Java HotSpot(TM) Client VM (build 1.3.0-C, interpreted mode)

#java -cp .t 
size of HashSet :2
true

======================================================================