在我的课堂上,我有字段int count
。我想根据count
变量的值创建一个新变量,如下所示:int a = new Integer(count)
.但是当我更新计数变量:count++
时,变量a
也会更新。那么如何创建非引用的 int 变量呢?
用Java做到这一点。 你最接近的赌注是创建一个带有单个 int 的封闭类,并改为引用它:
class MutableInteger {
public int value;
}
然后,稍后:
MutableInteger a = new MutableInteger();
a.value = 5;
MutableInteger b = a;
b.value++;
a.value++;
//since a.value is the same primitive as b.value, they are both 7
但是:这打破了Java中一系列普遍接受的最佳实践。您可能会寻找另一种方法来解决您的真正问题。
你描述的情况不会真正发生。
试试这个代码:
int count = 15;
int a = new Integer(count);
count++;
Window.alert("a is "+ a + " and count is " + count);
count
已更新,a
未更新。所以这意味着你在其他地方有错误。
尝试以下操作:
int a = count + 0;
你的问题有点误导。原因如下:
在 Java 中,原始值在复制时不会复制它们的引用。查看您的代码并查找您正在执行其他步骤的位置。
Integer
的构造函数使用以下内容:
this.integer = integer;