This simple Java code adds 2
to a set of long
, and subsequently prints whether 2
is a member of the set:
import java.util.*;
class A {
public static void main(String[] args) {
HashSet<Long> s = new HashSet<Long>();
long x = 2;
s.add(x);
System.out.println(s.contains(2));
}
}
It should print true
since 2
is in the set, but instead it prints false
. Why?
$ javac A.java && java A
false
HashSet does not have any method to retrieve the object from the HashSet. There is only a way to get objects from the HashSet via Iterator. When we create an object of HashSet, it internally creates an instance of HashMap with default initial capacity 16.
Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.
For HashSet, LinkedHashSet, and EnumSet, the add(), remove() and contains() operations cost constant O(1) time thanks to the internal HashMap implementation. Likewise, the TreeSet has O(log(n)) time complexity for the operations listed in the previous group.
Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).
Your set contains instances of Long
and you were looking for an Integer
(the type into which an int
is boxed when an Object
is required).
Test
System.out.println(s.contains(Long.valueOf(2)));
or
System.out.println(s.contains(2L));
When you say s.contains(2)
, it searches for 2
which by default is an int
, which gets boxed to Integer
. But the object which you stored was Long
. So, it returns false
Try using s.contains(Long.valueOf(2))
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With