Dog
Dog

Reputation: 7787

Java code using HashSet of longs doesn't work?

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

Upvotes: 18

Views: 15235

Answers (3)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382264

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

Upvotes: 25

Rahul Bobhate
Rahul Bobhate

Reputation: 5082

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.

Upvotes: 6

Juned Ahsan
Juned Ahsan

Reputation: 68715

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.

Upvotes: 1

Related Questions