-------android培训、java培训、期待与您交流! ----------
1.泛型的出现增强了java的类型安全,可以在编译期间对容器内的对象进行类型检查,在运行期不必进行类型转换。
而在j2se5之前必须在运行期动态进行容器内对象的检查及转换,泛型是编译时概念,运行时没有泛型减少含糊的容
器,可以定义什么类型的数据放入容器。
2.定义泛型
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));
}
}
3.类的静态方法不能使用泛型,因为泛型类是在创建对象的时候产生的。
class MyClass<E>{
public void show(E a){
System.out.println(a);
}public E get(){
return null;
}
}受限泛型
class MyClass <E extends Number>{
public void show(E a){
}
}
4.泛型与异常
类型参数在catch块中不允许出现,但是能用在方法的throws之后。例:
import java.io.*;
interface Executor<E extends Exception> {
void execute() throws E;
}
public class GenericExceptionTest {
public static void main(String args[]) {
try {
Executor<IOException> e = new Executor<IOException>() {
public void execute() throws IOException{
// code here that may throw an
// IOException or a subtype of
// IOException
}
};
e.execute();
} catch(IOException ioe) {
System.out.println("IOException: " + ioe);
ioe.printStackTrace();
}
}
}
5.泛型的一些局限型
不能实例化泛型 T t = new T(); //error
不能实例化泛型类型的数组
T[] ts= new T[10]; //编译错误
不能实例化泛型参数数
Pair<String>[] table = new Pair<String>(10); // ERROR
类的静态变量不能声明为类型参数类型
public class GenClass<T> {
private static T t; //编译错误
}
泛型类不能继承自Throwable以及其子类
public GenExpection<T> extends Exception{} //编译错误
不能用于基础类型int等
Pair<double> //error
Pair<Double> //right