Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HashSet and data type Short, incompatibility?

Running this code:

    public class SomeSet {

    public static void main(String[] args) {

        Set<Short> s = new HashSet<Short>();

        for (short i = 0; i < 100; i++) {

            s.add(i);

            s.remove(i - 1);

        }

        System.out.println(s.size());

    }

}

Will print the value 100.

Why does it print this value?

like image 424
Emerald Avatar asked Jun 07 '10 08:06

Emerald


People also ask

Does HashSet guarantee order?

No guarantee is made as to the iteration order of the set which means that the class does not guarantee the constant order of elements over time. It means that HashSet does not maintains the order of its elements.

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.

Is HashSet key value pair?

HashSet doesn't have key/value pairs. It is a Set of objects and you would use an implementer of Set to ensure that a collection of objects contained no duplicates. Implementers of Map like HashMap have key/value pairs and provide a get(Object key) method to get the value associated with a key.


1 Answers

s.remove(i - 1);

The line above will attempt to remove Integer objects from the set, because all integer calculations in Java have int (or long) results. Since the set contains Short objects, the remove() method will not have any effect.

This (and similar problems) is the main reason why you should almost never use short (and, more so, Short). Using a Set implementation to contain autoboxed numbers incurs a massive (easily 1000%) overhead, so it's rather pointless to try and save space by using Short rather than Integer.

like image 167
Michael Borgwardt Avatar answered Nov 15 '22 01:11

Michael Borgwardt