short and char auto unboxing in java

Sara :
   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?

Joe C :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=78459&siteId=1