为什么后增量在包装器类上起作用 [英] Why does post-increment work on wrapper classes

查看:86
本文介绍了为什么后增量在包装器类上起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在检查一些代码,并遇到一个实例,该实例后增加一个成员变量,该成员变量是Integer的包装器类.我自己尝试过,真的很惊讶.

I was doing a review of some code and came across an instance of someone post-incrementing a member variable that was a wrapper class around Integer. I tried it myself and was genuinely surprised that it works.

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

这将打印出0, 1,而不是我期望的0, 0.我已经浏览了语言规范,但找不到任何相关内容.谁能向我解释为什么这样有效,以及它在多个平台上是否安全?我以为这会分解成

This prints out 0, 1, not 0, 0 as I would have expected. I've looked through the language specification and can't find anything covering this. Can anyone explain to me why this works and if it's safe across multiple platforms? I would have thought that this would decompose into

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

但是很显然,规范中有一些内容使它在最后一行之前添加了x = temp1;.

But apparently there's something in the specification that make it add x = temp1; before the last line

推荐答案

跨平台使用绝对安全.在§15.4中指定了行为Java语言规范.a的.2(强调):

It's perfectly safe to use across platforms. The behavior is specified in §15.4.2 of the Java Language Specification (emphasis added):

后缀表达式的结果必须是可转换类型的变量(

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.

在运行时,如果对操作数表达式的求值突然完成,则后缀增量表达式由于相同的原因而突然完成,并且不会发生增量.否则,将值1加到变量的值上,并将总和存储回变量.在添加之前,二进制数值升级(§5.6.2)对值1和变量的值执行.如有必要,可以通过缩小原始转换来缩小总和(§5.1.3)和/或进行拳击转换(

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.

编辑,这与示例代码中发生的事情更为准确:

EDIT Here's a more accurate equivalent of what's going on in your example code:

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

这篇关于为什么后增量在包装器类上起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆