![《JDK5.0新特征全套课程》北风网原创[压缩包]](http://pic.dxspjc.com/dx_pic/9073113/5444117.jpg)
JDK5.0的11个主要新特征
1泛型(Generic)
1.1说明
![《JDK5.0新特征全套课程》北风网原创[压缩包]](http://pic.dxspjc.com/dx_pic/9073113/5444237.jpg)
![《JDK5.0新特征全套课程》北风网原创[压缩包]](http://pic.dxspjc.com/dx_pic/9073113/5444488.jpg)
增强了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> { ... }
例1:
public class MyList<Element> extends LinkedList<Element>
{
public void swap(int i, int j)
{
Element temp = this.get(i);
this.set(i, this.get(j));
this.set(j, temp);
}
public static void main(String[] args)
{
MyList<String> list = new MyList<String>();
list.add("hi");
list.add("andy");
System.out.println(list.get(0) + " " + list.get(1));
list.swap(0,1);
System.out.println(list.get(0) + " " + list.get(1));
}