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?
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With