17

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
Dog
  • 7,707
  • 8
  • 40
  • 74

3 Answers3

24

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)); 
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
6

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.

Rahul Bobhate
  • 4,892
  • 3
  • 25
  • 48
1

Your Hashset stores object of Long and not int/Integer.. You are trying to get an Integer where int is boxed while an Object is required.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136