short and char auto unboxing in java

Viewed 538
   HashSet charSet = new HashSet();
   for (char i = 0; i < 100; i++) {
      charSet.add(i);
      charSet.remove(i - 1);
    }
    System.out.println(charSet.size());

    HashSet intSet = new HashSet();
    for (int i = 0; i < 100; i++) {
        intSet.add(i);
        intSet.remove(i - 1);
    }
    System.out.println(intSet.size());

Output is 100 and 1 respectively.

I just realized that short and char do no get auto unboxed in Java. Why didn't the designers think it was important to do that?

2 Answers

This is actually nothing to do with boxing or unboxing.

When you apply an arithmetic operation to a char, it is converted to an int, as per JLS §5.6.2:

  1. Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
    • If either operand is of type double, the other is converted to double.
    • Otherwise, if either operand is of type float, the other is converted to float.
    • Otherwise, if either operand is of type long, the other is converted to long.
    • Otherwise, both operands are converted to type int.

Thus, i - 1 is not a char, but an int. And because there are no Integers in your charSet (only Characters), there is nothing to be removed. If you were to cast i - 1 to a char, you would get the result you are expecting.

I just realized that short and char do no get auto unboxed in Java. Why didn't the designers think it was important to do that?

Whatever has led you to this conclusion, it is incorrect.

Both short and char can be found in JLS Sec 5.1.8, Unboxing conversion.

It is easy to write code which demonstrates that both char and short undergo both autoboxing and auto unboxing:

Short ss = (short) 0;  // Autoboxing short to Short
short s = ss;          // Auto unboxing Short to short

Character cc = '\0';   // Autoboxing char to Character
char c = cc;           // Auto unboxing Character to char

Ideone demo

Related