递增Integer变量不会影响另一个引用同一对象的变量 [英] Incrementing an Integer variable doesn't affect another referencing the same object
问题描述
我总是理解静态变量在被引用时共享一个实例.我想对此进行测试,但结果与我预期的不同.
I always understood static variables to share one instance whenever they were referenced. I wanted to put this to the test but the results were different than I had expected.
static Integer counter = 0;
static Integer test = counter;
public static void main(String args[]) {
counter++;
System.out.println("counter: " + counter);
System.out.println("test: " + test);
}
输出:
计数器:1
测试:0
因为 test
引用了 counter
,所以我认为当我增加 counter
时, test
也会自动增加.但是,似乎 test
从某个地方引用了 0
,问题是在哪里?
Since test
references counter
I thought that when I increment counter
then test
will automatically be incremented as well. However, it seems test
is referencing 0
from somewhere, question is, where?
推荐答案
由于
test
引用了counter
这个假设是错误的.在Java中,您不能引用变量.存储在变量中的是一个值.该值可以是原始类型值或引用类型值.对于基元,值是基元的值.对于引用类型,
This assumption is false. In Java, you cannot reference variables. What is stored in a variable is a value. That value can either be a primitive type value or a reference type value. In the case of primitives, the value is the value of the primitive. In the case of reference types,
在
int a = 0;
int b = a;
对变量 a
求值以生成值 0
,并将该值存储在 b
中.
the variable a
is evaluated to produce a value, 0
, and that value is stored in b
.
在
Integer a = 0;
Integer b = a;
0
通过 Integer.valueOf(int)
和值(对 Integer
对象存储在 a
中.然后对 a
进行求值,生成对该 Integer
对象的引用的值,并将该值存储在 b
中.
0
is converted to an Integer
through Integer.valueOf(int)
and the value, a reference to an Integer
object is stored in a
. Then a
is evaluated, producing the value of that reference to an Integer
object, and that value is stored in b
.
这与
此外,变量是 static
的事实是无关紧要的.
Also, the fact that the variables are static
is irrelevant.
解决此问题的唯一方法是手动更新 test
,即
The only way around this is to update test
manually i.e.
counter++;
test = counter;
这篇关于递增Integer变量不会影响另一个引用同一对象的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!