Java: various outputs when adding / removing short and integer elements in a set

I was not sure how to ask this question. But what is the difference between these two 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

Output 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

Output 100

+3
source share
3 answers

The type of expression i - 1is equal intbecause all operands in an integer arithmetic expression expand at least to int. Set<Short>has add(Short)and remove(Object), therefore remove, casting / autoboxing is not required for the call . Therefore, you are trying to remove s Integerfrom the set Short.

, Set<Number>:

final Set<Number> ns = new HashSet<>();
final short s = 1;
ns.add(s);
ns.add(s+0);
ns.add(s+0L);
System.out.println(ns); // prints [1, 1, 1]

, TreeSet, , ​​ ClassCastException, .

, , . Java.

+11

99, , , 98.

Integer, Short, - .

(i) int Integer.

, :

Set<Short> a = new HashSet<Short>();
        for (Short i = 0; i < 100; i++) {
            a.add(i);
            a.remove(i);
        }

, , - 1, , .

+3

You cannot remove Integer from a set of shorts without casting.

+2
source

All Articles