Java code using HashSet of longs doesn't work?

Dog picture Dog · Jun 3, 2013 · Viewed 9.5k times · Source

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

Answer

Denys S&#233;guret picture Denys Séguret · Jun 3, 2013

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));