問(wèn)題描述
考慮這段代碼:
class test {
public static void main(String[] args) {
test inst_test = new test();
int i1 = 2000;
int i2 = 2000;
int i3 = 2;
int i4 = 2;
Integer Ithree = new Integer(2); // 1
Integer Ifour = new Integer(2); // 2
System.out.println( Ithree == Ifour );
inst_test.method( i3 , i4 );
inst_test.method( i1 , i2 );
}
public void method( Integer i , Integer eye ) {
System.out.println(i == eye );
}
}
打印出來(lái):
false
true
false
我理解第一個(gè) false
,== 運(yùn)算符只檢查兩個(gè)引用是否在同一個(gè)對(duì)象上工作,在這種情況下不是.
I understand the first false
, the == operator only checks if two references are working on the same object, which in this case aren't.
下面的 true
和 false
讓我摸不著頭腦.為什么 Java 會(huì)認(rèn)為 i3
和 i4
相等但 i1
和 i2
不同?兩者都被包裝成整數(shù),不應(yīng)該 both 評(píng)估為假嗎?這種不一致是否有實(shí)際原因?
The following true
and false
have me scratching my head. Why would Java consider i3
and i4
equal but i1
and i2
different? Both have been wrapped to Integer, shouldn't both evaluate to false? Is there a practical reason for this inconsistency?
推薦答案
將基元自動(dòng)裝箱到對(duì)象中(在您對(duì) method
的調(diào)用中使用的方法是使用小值緩存.來(lái)自 Java 語(yǔ)言規(guī)范第 5.1.7 節(jié):
Autoboxing of primitives into objects (as used in your calls to method
uses a cache of small values. From the Java Language Specification section 5.1.7:
如果被裝箱的值p為真,false,一個(gè)字節(jié),一個(gè)字符在范圍內(nèi)u0000 到 u007f,或者一個(gè) int 或 short介于 -128 和 127 之間的數(shù)字,然后讓r1 和 r2 是任意兩個(gè)的結(jié)果p的拳擊轉(zhuǎn)換.它總是r1 == r2 的情況.
If the value p being boxed is true, false, a byte, a char in the range u0000 to u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.
緊隨其后的規(guī)范討論部分也很有趣.值得注意的是,如果 JVM 愿意,它可以緩存 更多 值 - 你不能確定這樣做的結(jié)果:
The discussion part of the spec immediately following that is interesting too. Notably a JVM can cache more values if it wants to - you can't be sure of the results of doing:
Integer i1 = 129;
Integer i2 = 129;
boolean b = (i1 == i2);
這篇關(guān)于java的行為不一致==的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!