自動裝箱/拆箱 (Auto-Boxing/Unboxing)
沒有自動裝箱/拆箱:
int int1 = 1;
Integer integer2 = new Integer(int1);
int int3 = integer2.intValue();
有自動裝箱/拆箱:
int int1 = 1;
Integer integer2 = int1; // 自動裝箱
int int3 = integer2; // 自動拆箱
泛型 (Generic Types)
泛型就像是C++的模板。原有的Collection API加上泛型支援後,增加對型別的檢查,減 少程式錯誤的機會。
沒有泛型:
HashMap hm = new HashMap();
int i=1;
String tt="test";
hm.put(new Integer(i), tt);
使用Generic:
HashMap <Integer, String>hm = new HashMap<Integer, String> ();
int i=1;
String tt = "test";
hm.put(i, tt); // 在這裏對int自動裝箱成Integer,也使用了參數的型別檢查
自動裝箱的新功能,可能是從C#語言身上學習來的,Java 已經越來越像C#。然而Java對 自動裝箱/拆箱的支援,僅是利用編譯器實現,在Java Bytecode 中,並無自動裝箱/拆箱的 作業碼 (opcode)。
注釋 (Annotation)
Annotation全名是Program Annotation Facility ,是Java SE 5.0的新功能。Java 的 Annotation 類似於 .NET 的屬性 (Attribute)。Java 的注釋是一種介面 (interface),繼 承自 java.lang.annotation.Annotation。Class File 則貼上 ACC_ANNOTATION 標籤。
// JDK 1.4
/**
* @todo to be implemented
**/
void gimmeSomeLoving() {
throw new Exception("not implemented");
}
// JDK 1.5
@todo void gimmeSomeLoving() {
throw new Exception("not implemented");
}