java 中的 short 和 char 自动拆箱

short and char auto unboxing in java

   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());

输出分别为100和1。

我刚刚意识到 short 和 char 在 Java 中不会自动拆箱。为什么设计师不认为这样做很重要?

这实际上与装箱或拆箱无关。

当您对 char 应用算术运算时,它会根据 JLS §5.6.2:

转换为 int
  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.

因此,i - 1 不是 char,而是 int。而且因为你的 charSet 中没有 Integer(只有 Character),所以没有什么要删除的。如果您将 i - 1 转换为 char,您将得到您期望的结果。

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?

无论是什么让您得出这个结论,都是不正确的。

shortchar 都可以在 JLS Sec 5.1.8, Unboxing conversion 中找到。

很容易编写代码来演示 charshort 都进行自动装箱和自动拆箱:

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

Character cc = '[=10=]';   // Autoboxing char to Character
char c = cc;           // Auto unboxing Character to char

Ideone demo