我有一个简单的代码片段来测试“不可变”整数,如下所示:
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是不可变的。
让我感到困惑的是,main()中的++i`为什么会在传递到函数时增加值,而不会改变呢?
我想知道Java编译器或JVM是如何实现这一点的?我知道Integer是一个引用类型,所以当作为参数传递时,会传递一个引用,然后++i会更改它的包装值?
希望有技术上的解释。
发布于 2022-06-24 04:31:17
自动装箱和反装箱是编译器帮助我们在原始类型和包装类之间进行交互的自动转换。
https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.1说:
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
所以,++i等于i = Integer.valueOf(i.intValue() + 1)
https://stackoverflow.com/questions/72738617
复制相似问题