Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 557
Dog Avatar asked Jun 03 '13 16:06

Dog


People also ask

Why HashSet has no get method?

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.

How do I allow duplicates in HashSet?

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.

What is the time complexity of HashSet in Java?

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.

What is the default size of HashSet in Java?

Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).


2 Answers

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)); 
like image 123
Denys Séguret Avatar answered Oct 05 '22 23:10

Denys Séguret


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.

like image 34
Rahul Bobhate Avatar answered Oct 05 '22 22:10

Rahul Bobhate