指向同一个Integer对象的变量之间的比较 [英] Comparison between variables pointing to same Integer object
本文介绍了指向同一个Integer对象的变量之间的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当前节目的输出是奇怪的。但两个变量共享相同的参考。为什么第二次和第三次比较不正确?
The output of current program is "Strange". But both the variables share the same reference. Why are the second and third comparisons not true?
Integer a;
Integer b;
a = new Integer(2);
b = a;
if(b == a) {
System.out.println("Strange");
}
a++;
if(b == a) {
System.out.println("Stranger");
}
a--;
if(b == a) {
System.out.println("Strangest");
}
输出:奇怪
推荐答案
这是autoboxing的工件,以及Integer在Java中不可变的事实。
That's the artifact of autoboxing and a fact that Integer is immutable in Java.
a ++
和 a -
大致翻译成这个。
int intA = a.getInt( );
intA++;
a = Integer.valueOf( intA ); // this is a reference different from b
这篇关于指向同一个Integer对象的变量之间的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文