JVM如何使原型包装器“不变”传递功能参数时?

发布于 2025-02-10 04:24:39 字数 582 浏览 3 评论 0 原文

我有一个简单的代码段来测试以下“不可变”整数:

    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 是一个参考类型,因此当传递参数时,传递了一个参考,然后++我将更改其包装值吗?

希望技术解释。

I have a simple code snippet to test "Immutable" integer like below:

    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!
    }

I could see as Java language design, a wrapper class Integer is immutable when passed as function parameter.

What confused me is, why the ````++i``` inside main() will increase the value, while passing into function, doesn't change?

I wonder how does Java compiler or JVM achieve this? I know that Integer is a reference type, so when passed as parameter, an reference is passed, and then ++i will change its wrapped value?

Wish technical explanation.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

Oo萌小芽oO 2025-02-17 04:24:40

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 to i = Integer.valueOf(i.intValue() + 1)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文