Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java GWT。创建基元(无引用)整数变量_Java - Fatal编程技术网

Java GWT。创建基元(无引用)整数变量

Java GWT。创建基元(无引用)整数变量,java,Java,在我的课堂上,我有fieldint count。我想根据count变量的值创建一个新变量,如下所示:inta=newinteger(count)。但当我更新count变量时:count++,变量a也会更新。那么如何创建非引用int变量呢 使用Java无法做到这一点。最接近的方法是创建一个包含单个int的封闭类,并引用该类: class MutableInteger { public int value; } 然后,稍后: MutableInteger a = new MutableIn

在我的课堂上,我有field
int count
。我想根据
count
变量的值创建一个新变量,如下所示:
inta=newinteger(count)
。但当我更新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中一系列公认的最佳实践。您可能会寻找一种替代方法来解决您真正的问题。

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 count = 15;
int a = new Integer(count);
count++;
Window.alert("a is "+ a + " and count is " + count); 
count
已更新,而
a
未更新。因此,这意味着您在其他地方出错。

请尝试以下操作:

int a = count + 0;
请尝试以下操作:

int a = count + 0;

你的问题有些误导。原因如下:

在Java中,原语值在被复制时,其引用不会被复制。 查看您的代码并查找您正在执行的附加步骤

Integer
的构造函数使用以下内容:

this.integer = integer;

你的问题有些误导。原因如下:

在Java中,原语值在被复制时,其引用不会被复制。 查看您的代码并查找您正在执行的附加步骤

Integer
的构造函数使用以下内容:

this.integer = integer;

+1-只是好奇,你指的这个中断的最佳实践是什么?+1-只是好奇,你指的这个中断的最佳实践是什么?你应该解释一下这会有什么帮助,以便清楚你的答案解决了什么。问题是如何在2个整数上中断相同的引用。我的例子解决了这个问题。怎么了?或者可能是我不太明白问题是什么。我很抱歉,如果你要解释这会有什么帮助,那么你的答案就很清楚了。问题是如何在2个整数上打破相同的引用。我的例子解决了这个问题。怎么了?或者可能是我不太明白问题是什么。如果是这样,我很抱歉