JDK1.5中新的語言特征 -- 自動(dòng)置入/自動(dòng)取出(Autoboxing/unboxing)
Java有基本數(shù)據(jù)類型,在這些基本數(shù)據(jù)類型周圍又有包裝類。通常,編程人員需要將一種類型轉(zhuǎn)換成另一種。看看Listing C.中的代碼片斷。Listing C
public class Employee {
private static final Integer CHILD = new Integer(0);
public static void main(String args[]) {
//code for adding n to an Integer
int n=10;
Integer age= new Integer(30);
Integer ageAfterTenYear= new Integer(age.intValue +10);
}
}
請(qǐng)注意,用于計(jì)算ageAfterTenYear的內(nèi)循環(huán)代碼看上去是多么雜亂。現(xiàn)在,在Listing D.中看看相同的程序使用autoboxing重寫后的樣子。
Listing D
public class Employee {
public static void main(String args[]) {
int n=10;
Integer age= new Integer(30);
Integer ageAfterTenYear= age +10;
}
}
有一件事值得注意的:在先前,如果你取出(unbox)Null值,它將變?yōu)?。在次代碼中,編譯器將自動(dòng)地轉(zhuǎn)換Integer為int然后加上10,接著將其轉(zhuǎn)換回Integer.。
posted on 2005-09-12 16:05 風(fēng) 閱讀(590) 評(píng)論(0) 編輯 收藏