Java 5.0

此條目需要擴充。 (2010年9月27日) |
此條目没有列出任何参考或来源。 (2010年9月27日) |
JAVA 從5.0版本開始,加入許多新特性,是JAVA歷史中修改最大的版本,許多特點模仿自C#,因而被認為是為了與C#對抗。
新的特性
自動裝箱/拆箱 (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標籤。
從5.0開始,javadoc的@deprecated
(代表不建議使用的方法或類別)也被Annotation中的@Deprecated
取代;另外,使用Java 實作SOP的AspectJ與Spring也使用了大量的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");
}
枚举类型 (enum)
枚举类型也是J2SE 5.0的新功能。過去Java認為enum的關鍵字是不必要的功能,因為用public static int field就可以取代enum,因此過去一直不用。J2SE 5.0中的class如果是enum,在class file中會被貼上一個ACC_ENUM標籤。
// JDK 1.4
class JavaTech {
public static final int J2ME = 1;
public static final int J2SE = 2;
public static final int J2EE = 3;
}
// JDK 1.5
public enum NewJavaTech {
J2ME, J2SE, J2EE
}
输入输出
在jdk1.5及其以後版本中,java.util.Scanner
和java.util.Formatter
類別被应用到輸入輸出中。另外,也出現了printf()
函式。
国际化
Java语言严格区分字节和字符。字符的存储格式为UCS-2,也就是只能使用位於基本多文種平面的字元,从Java 5开始支持UTF-16字符。
另外,從5.0開始Java的程式也開始可以使用Unicode字元進行命名。
下面就是一個合法的Java程式,裡面包含了中文字符作為字串的名稱,這個程式可以在编譯器中通過編譯。
public class HelloWorld {
private string 文本 = "HelloWorld";
}
其它
- foreach 迴圈
- 可變長度的引數
引發的問題
Java 5.0雖然加入許多的新特性,但為了與舊版本相容,JVM並沒有隨之改變,而僅只是從編譯器動手腳,因而引發許多問題。
自動裝箱/拆箱的矛盾
自動裝箱這功能也造成了一些矛盾,例如:
Integer int1 = new Integer(1);
Integer int2 = new Integer(1);
System.out.println(int1 >= int2); // 檢查兩者的值, true
System.out.println(int1 <= int2); // 檢查兩者的值, true
System.out.println(int1 != int2); // 檢查兩者的參考位置,true!
擦拭的泛型
和C#,C++的泛型不同,Java的泛型只用在型別檢查,使用的時候還要再做一次轉型。