首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JVM在传递函数参数时如何使原始类型包装器“不可变”?

JVM在传递函数参数时如何使原始类型包装器“不可变”?
EN

Stack Overflow用户
提问于 2022-06-24 03:13:20
回答 1查看 49关注 0票数 0

我有一个简单的代码片段来测试“不可变”整数,如下所示:

代码语言:javascript
复制
    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会更改它的包装值?

希望有技术上的解释。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72738617

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档