JVM如何使原型包装器“不变”传递功能参数时?
我有一个简单的代码段来测试以下“不可变”整数:
public static void changeInteger(Integer i) {
++i;
}
public static void main(String[] args) {
Integer i = new Integer(3);
++i;
System.out.println(i); // 4
ImmutableWrapper.changeInteger(i);
System.out.println(i); // still 4!
}
我可以将其视为Java语言设计,包装器类 Integer
作为函数参数传递时是不可变的。
我感到困惑的是,为什么````````````'++ i''内部()在传递到函数时会增加值,而不会改变?
我想知道Java编译器或JVM如何实现这一目标?我知道 Integer
是一个参考类型,因此当传递参数时,传递了一个参考,然后++我将更改其包装值吗?
希望技术解释。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
自动转换和拆箱是编译器帮助我们在原始类型和包装器类之间进行交谈的自动转换。
说:
,如有必要,总和由缩小原始转换(§5.1.3)和/或进行拳击转换(第5.1.7节)的范围缩小,然后将其缩小到该变量存储之前的类型。前缀增量表达式的值是存储新值后变量的值
因此,
++ i
等于i = integer.valueof(i.intvalue()+1)
Autoboxing and unboxing is the automatic conversion that compiler helps us to converse between the primitive types and wrapper classes.
https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.1 says:
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 prefix increment expression is the value of the variable after the new value is stored
So,
++i
equals toi = Integer.valueOf(i.intValue() + 1)