gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:05:58 24 4
gpt4 key购买 nike

我在审查一些代码时遇到了一个实例,有人后递增了一个成员变量,它是一个围绕 Integer 的包装类。我自己尝试过,真的很惊讶它的效果。

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

这会打印出 0, 1,而不是我预期的 0, 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 (§5.1.8) 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 (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) 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());

关于java - 为什么后增量适用于包装类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13280134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com