编程语言
首页 > 编程语言> > java – 为什么后期增量适用于包装类

java – 为什么后期增量适用于包装类

作者:互联网

我正在对一些代码进行审查,并且遇到了一个有人在增加一个成员变量的实例,该成员变量是一个围绕Integer的包装类.我亲自尝试过,真的很惊讶它有效.

Integer x = 0; 
System.out.print(x++ + ", ");
System.out.print(x);

这打印出0,1,而不是0,正如我预期的那样.我查看了语言规范,找不到任何涉及此内容的内容.任何人都可以向我解释为什么它可以工作,如果它在多个平台上是安全的?我原本以为这会分解成

Integer x = 0;
int temp1 = x.intValue();
int temp2 = temp1 + 1;
System.out.println(temp1);
temp1 = temp2;
System.out.println(x.intValue());

但显然规范中有一些东西使它添加x = temp1;在最后一行之前

解决方法:

跨平台使用是完全安全的.行为在§15.4.2 of the Java Language Specification中指定(强调添加):

The result of the postfix expression must be a variable of a type that is convertible (07001) to a numeric type, or a compile-time error occurs.

The type of the postfix increment expression is the type of the variable. The result of the postfix increment expression is not a variable, but a value.

At run-time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (07002) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (07003) and/or subjected to boxing conversion (07004) to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable before the new value is stored.

编辑这里更准确地等同于您的示例代码中发生的事情:

Integer x = 0;
int temp = x.intValue();
x = temp + 1; // autoboxing!
System.out.println(temp + ", ");
System.out.println(x.intValue());

标签:post-increment,java,immutability
来源: https://codeday.me/bug/20191002/1843251.html