2013-04-13 29 views
5

例如,看一下這個代碼:如果包裝器使用拆箱,那麼intValue()方法的需要是什麼?

Integer myInt = new Integer(5); 
int i1 = myInt.intValue(); 
int i2 = myInt; 

System.out.println(i1); 
System.out.println(i2); 

正如你所看到的,我已經從包裝抄襲我的整數值primive的方法有兩種:

我可以使用拆箱

OR

我可以使用該方法的intValue()

所以...什麼是有方法的時候已經有的需要拆箱?

回答

9

拆箱是在Java 5中引入的。從原始版本開始,包裝(包括此方法)就已存在。

的鏈接Javadoc

在當時(1996年),我們確實需要的intValue()方法和甲骨文保證向後的向後兼容性......達到一定水平(並不總是在重大的版本100% )。

的方法必須留在。

+0

所以,今天我用JDK7想這是最好使用比拆箱舊的intValue()。 – user1883212

+0

@ user1883212就像DeltaLima在他的回答中所展示的那樣,拳擊/拆箱可以給出一些奇怪的結果,只要你知道你在做什麼就可以隨意使用這兩個系統中的任何一個。 – Frank

7

除了弗蘭克的答案,給出了一個很好的歷史的角度還是有需要使用今天intValue()在某些情況下。

注意以下陷阱那就說明你不能把一個Integerint的:

Integer i1 = new Integer(5); 
Integer i2 = new Integer(5); 

//This would be the way if they were int 
System.out.println(i1 == i2); //Returns false 

//This is the way for Integers 
System.out.println(i1.intValue()==i2.intValue()); //Returns true 
System.out.println(i1.equals(i2)); //Returns true 

返回

false 
true 
true 
+0

誰知道這造成了多少困惑的凝視和劃痕頭。在對容器進行索引並嘗試比較值時,出乎意料地遇到這種情況是相當典型的。例如。 'List A;'A.get(i)== A.get(i - 1)'返回'false',即使這兩個位置都包含「Integer(5)」...... – AndrewJC

相關問題