跳转到内容

Java 5.0

维基百科,自由的百科全书

这是本页的一个历史版本,由Persianbeats留言 | 贡献2010年9月26日 (日) 10:17 建立内容为“JAVA 從5.0版本開始,加入許多新特性,是JAVA歷史中修改最大的版本,主要目的是為了與C#對抗。 == 新的特性 == === ...”的新頁面)编辑。这可能和当前版本存在着巨大的差异。

(差异) ←上一修订 | 最后版本 (差异) | 下一修订→ (差异)

JAVA 從5.0版本開始,加入許多新特性,是JAVA歷史中修改最大的版本,主要目的是為了與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;         // 自動拆箱


不過自動裝箱這功能也造成了一些矛盾,例如:

 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!


泛型 (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");
 }

枚举类型 (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.Scannerjava.util.Formatter類別被应用到輸入輸出中。另外,也出現了printf()函式。

国际化

Java语言严格区分字节字符。字符的存储格式为UCS-2,从Java 5开始支持UTF-16字符。Java的程序遂可以使用Unicode字符进行书写。

下面就是一个合法的Java程序,裡面包含了中文字符作为类的名称而不是字符串,这个程序可以在编译器中运行通过。

public class HelloWorld {
   private string 文本 = "HelloWorld";
}

其它