問題描述
我正在閱讀 Kathy Sierra 和 Bert Bates 的 SCJP Java 6,這本書讓我非常困惑.在第 245 頁上,他們聲明以下代碼.
I'm reading SCJP Java 6 by Kathy Sierra and Bert Bates and this book is confusing me so much. On page 245 they state that the following code below.
Integer i1 = 1000;
Integer i2 = 1000;
if(i1 != i2)
System.out.println("different objects");
//Prints output
different objects
然后在下一頁他們有以下代碼
Then on the very next page they have the following code
Integer i3 = 10;
Integer i4 = 10;
if(i3 == i4)
System.out.println("same objects");
//Prints output
same objects
我很困惑!當我自己嘗試時,您似乎無法使用 == 來比較使用 equals() 方法的相同方式.即使整數變量設置為相同的值(即 10),使用 == 總是會給我假".我對么?使用 == 比較相同的 Integer 對象(具有相同的值)將始終導致 'false'
I'm so confused! When I try this out on my own it seems that you cannot use the == to compare the same way you would use equals() method. Using the == always gives me 'false' even if the Integer variables are set to the same value (i.e. 10). Am I correct? Using the == to compare the same Integer object (with same values) will always result in 'false'
推薦答案
答案的關鍵就叫object interning.Java 實習生的數字很小(小于 128),因此所有 Integer(n)
的實例與 n
在實習范圍內都是相同的.大于或等于 128 的數字不會被保留,因此 Integer(1000)
對象彼此不相等.
The key to the answer is called object interning. Java interns small numbers (less than 128), so all instances of Integer(n)
with n
in the interned range are the same. Numbers greater than or equal to 128 are not interned, hence Integer(1000)
objects are not equal to each other.
這篇關于在 Java 中使用 == 運算符比較包裝器對象的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!