為什么要裝箱
我們都知道Java中有基本數(shù)據(jù)類型,并且基本數(shù)據(jù)類型不屬于類的范疇搪泳。但是在一些情況下侠畔,比如泛型設(shè)計時泛型只能是Object類型,舉例List<T>,其中T必須是Object和Object的子類毛萌。如果我們想在List中存放int數(shù)值時,List<int>是不合法的喝滞。為了解決這一類問題阁将,就有了裝箱的概念。
這時我們需要一個類來對應(yīng)一個基本數(shù)據(jù)類型右遭,已Integer為例:
class Integer{
int i;
Integer(int i){
this.i = i;
}
int intValue(){
return i;
}
}
我們在List<Integer>中存放Integer對象做盅,就間接地打到了我們在List集合中存放int數(shù)值的目的。
為什么要拆箱
拆箱和裝箱對應(yīng)窘哈,我們?yōu)榱藢緮?shù)據(jù)類型進行操作將其裝箱吹榴,但是在實際使用時我們關(guān)注的還是他的數(shù)值。例如我們需要對List<Integer>中的數(shù)據(jù)進行排序滚婉,那么必然需要對每個元素進行比較大小图筹,這時我們就需要獲得每個Integer對象所表示的數(shù)值,這個獲取數(shù)值過程就是拆箱過程让腹。
裝箱和自動裝箱
Integer i1 = new Integer(1);//裝箱
Integer i2 = 1;//自動裝箱
通過上述兩種方式都可以實現(xiàn)裝箱远剩,即找到一個Integer類型的對象與int數(shù)值1對應(yīng)。自動裝箱其實就是Java幫祝我們自動完成了裝箱過程骇窍。自動裝箱簡化了我們代碼瓜晤,使代碼更簡潔直觀。
拆箱和自動拆箱
Integer i = 1;//自動裝箱
int n = i;//自動拆箱
int m = i.intValue();//拆箱
知識多
- byte腹纳、short痢掠、int==自動==裝箱時,如果數(shù)值在[-128,127]的取值范圍內(nèi)嘲恍,裝箱不會創(chuàng)建新的對象足画,會直接復(fù)用內(nèi)存中預(yù)先創(chuàng)建好的對象。手動裝箱則每次都會產(chǎn)生新的對象蛔钙。
Integer l = new Integer(1);
Integer m = 1锌云;
Integer n = 1;
System.out.println(l == m);//false
System.out.println(m == n);//true
如果裝箱數(shù)值不在這個范圍內(nèi)吁脱,則會創(chuàng)建不同的對象桑涎。
Integer m = 200;
Integer n = 200兼贡;
System.out.println(m == n);//false
System.out.println(m.equals(n));//true
- boolean攻冷、char自動裝箱復(fù)用內(nèi)存中的對象。
Boolean b1 = true;
Boolean b2 = true;
Boolean b3 = true;
System.out.println(b1 == b2);//true
System.out.println(b1.equals(b2));//true
System.out.println(b2 == b3);//false
System.out.println(b2.equals(b3));//true
Character c1 = 'A';
Character c2 = 'A';
System.out.println(c1 == c2);//true
System.out.println(c1.equals(c2));//true
- float遍希、double等曼、long自動裝箱時每次都會創(chuàng)建不同的對象。
Float f1=1.0f;
Float f2=1.0f;
System.out.println(f1 == f2);//false
System.out.println(f1.equals(f2));//true
- 包裝器類型進行equals比較內(nèi)容時,如果不是相同類型禁谦,返回false胁黑。
Float f = 1.0f;
Double d = 1.0;
System.out.println(f.equals(d));//false
原因是包裝器類型的equals方法在比較內(nèi)容之前,都會先判斷是否屬于相同類型州泊,以Float的equals方法為例丧蘸。
public boolean equals(Object obj) {
return (obj instanceof Float)&& (floatToIntBits(((Float)obj).value) == floatToIntBits(value));
}
- 裝箱和拆箱操作只針對基本數(shù)據(jù)類型,以下代碼不是裝箱和拆箱遥皂。
String s1 = new String("a");
String s2 = "a";
String s3 = s1;
String s4 = s2.toString();