JDK5.0的11个主要新特征[1]

[入库:2006年2月23日] [更新:2007年3月24日]

本文简介:

1           泛型(Generic)

1.1          说明

增强了java的类型安全,可以在编译期间对容器内的对象进行类型检查,在运行期不必进行类型的转换。而在j2se5之前必须在运行期动态进行容器内对象的检查及转换

减少含糊的容器,可以定义什么类型的数据放入容器

ArrayList<Integer> listOfIntegers; // <TYPE_NAME> is new to the syntax

Integer integerObject;

listOfIntegers = new ArrayList<Integer>(); // <TYPE_NAME> is new to the syntax

listOfIntegers.add(new Integer(10)); // 只能是Integer类型

integerObject = listOfIntegers.get(0); // 取出对象不需要转换

1.2          用法

声明及实例化泛型类:

HashMap<String,Float> hm = new HashMap<String,Float>();

//不能使用原始类型

GenList<int> nList = new GenList<int>();  //编译错误

J2SE 5.0目前不支持原始类型作为类型参数(type parameter)

定义泛型接口:

public interface GenInterface<T> {

    void func(T t);

}

定义泛型类:

public class ArrayList<ItemType> { ... }

public class GenMap<T, V> { ... }

本文关键:JDK5.0的11个主要新特征
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top