I wasn't sure on how to ask this question. But, what is the different between these 2 lines of code?
Set<Integer> a = new HashSet<Integer>();
for (int i = 0; i < 100; i++) {
a.add(i);
a.remove(i - 1);
}
System.out.println(a.size());
I expected 99 to be the output
Output is 1
Set<Short> a = new HashSet<Short>();
for (Short i = 0; i < 100; i++) {
a.add(i);
a.remove(i - 1);
}
System.out.println(a.size());
I expected 99 to be the output
Output is 100
The first one will remove all number except 99 because the last number you remove is 98.
In the second you are trying to remove an Integer, but your type is Short, so it does not remove any element.
On the first one, you do
add(i)
theint
is automatically converted to anInteger
.On the second if you had done the following:
It would remove all the elements because you add a short and remove short, but because you did
i - 1
you are not adding a short, but an integer.You can't remove Integer from Set of shorts without casting.
The type of the expression
i - 1
isint
because all operands in an integer arithmetic expression are widened to at leastint
.Set<Short>
hasadd(Short)
andremove(Object)
so there's no casting/autoboxing needed on theremove
call. Therefore you are trying to removeInteger
s from a set ofShort
s.Note that for this reason it almost never makes sense to declare a
Set<Number>
:As a bonus round, if you change the set implementation to
TreeSet
, the magic disappears and it throws aClassCastException
, giving away the trick.Deep down, this issue has to do with the fact that equality is a symmetric relation, which must not distinguish the right hand side from the left hand side. These semantics are impossible to achieve with Java's single-dispatch methods.