编程语言
首页 > 编程语言> > Java中的short和char自动拆箱

Java中的short和char自动拆箱

作者:互联网

   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中没有整数(只有字符),因此没有要删除的内容.如果将i-1转换为字符,则将得到期望的结果.

标签:unboxing,java
来源: https://codeday.me/bug/20191024/1924429.html