gpt4 book ai didi

java - 操作整数对象而不创建新实例?

转载 作者:行者123 更新时间:2023-12-01 19:42:00 24 4
gpt4 key购买 nike

我有:

// lets call this Integer reference ABC101
Integer i = new Integer(5);

//j points to i so j has the reference ABC101
Integer j = i;

//creates a new Integer instance for j?
j++;
//I want j++ to edit and return ABC101
System.out.println(i); // 5 not 6

所以我的目标是通过具有相同引用的不同对象来操纵 I 而无需切换引用。不,不要说,“你为什么不直接使用整数或者你为什么不直接扰乱我”。这不是本练习的目的。总是有更简单的方法来做事,但这就是我应该处理的事情。最后一个问题...这是否意味着 Integer 对象是不可变的?

最佳答案

事实上,所有基元(int、boolean、double 等)及其各自的包装类都是不可变的。

无法使用后自增运算符j++来更改i的值。这是因为 j++ 转换为 j = j + 1 并且赋值运算符 = 意味着 i 和 j 不再引用同一个对象。

你可以做的是使用 int 数组(或 Integer,无论你喜欢什么)。您的代码将如下所示

int i[] = {5};

int j[] = i;

j[0]++;
System.out.println(i[0]); // prints 6

但是不建议这样做。在我看来,你应该使用自己的 int 包装类,如下所示

public class MutableInt

private int i;
public MutableInt(int i) {
set(i);
}

public int get() {
return i;
}

public void set(int i) {
this.i = i;
}

public void increment() {
i++;
}

// more stuff if you want to

请注意,您将无法以这种方式使用自动装箱,并且没有像 java.lang.Integer 那样的缓存

关于java - 操作整数对象而不创建新实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55051282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com