問題描述
考慮這段代碼:
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 );
}
}
打印出來:
false
true
false
我理解第一個 false
,== 運算符只檢查兩個引用是否在同一個對象上工作,在這種情況下不是.
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 會認為 i3
和 i4
相等但 i1
和 i2
不同?兩者都被包裝成整數,不應該 both 評估為假嗎?這種不一致是否有實際原因?
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?
推薦答案
將基元自動裝箱到對象中(在您對 method
的調用中使用的方法是使用小值緩存.來自 Java 語言規范第 5.1.7 節:
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,一個字節,一個字符在范圍內u0000 到 u007f,或者一個 int 或 short介于 -128 和 127 之間的數字,然后讓r1 和 r2 是任意兩個的結果p的拳擊轉換.它總是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.
緊隨其后的規范討論部分也很有趣.值得注意的是,如果 JVM 愿意,它可以緩存 更多 值 - 你不能確定這樣做的結果:
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);
這篇關于java的行為不一致==的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!