Welcome 微信登录

首页 / 软件开发 / JAVA / Java 5.0的特性

Java 5.0的特性2011-04-23自动装箱/拆箱 (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");
}