java中的java5.0的泛型2(J2SE入门24)

泛型方法的定义
把数组拷贝到集合时,数组的类型一定要和集合的泛型相同。
<...>定义泛型,其中的"..."一般用大写字母来代替,也就是泛型的命名,其实,在运行时会根据实际类型替换掉那个泛型。

<E> void copyArrayToList(E[] os,List<E> lst){
for(E o:os){
lst.add(o);
}
}
static <E extends Number> void copyArrayToList(E[] os,List<E> lst){
for(E o:os){
lst.add(o);
}
}
static<E extends Number & Comparable> void copyArrayToList(E[] os,List<E> lst){
for(E o:os){
lst.add(o);
}
}



受限泛型是指类型参数的取值范围是受到限制的. extends关键字不仅仅可以用来声明类的继承关系, 也可以用来声明类型参数(type parameter)的受限关系.例如, 我们只需要一个存放数字的列表, 包括整数(Long, Integer, Short), 实数(Double, Float), 不能用来存放其他类型, 例如字符串(String), 也就是说, 要把类型参数T的取值泛型限制在Number极其子类中.在这种情况下, 我们就可以使用extends关键字把类型参数(type parameter)限制为数字
只能使用extends不能使用 super,只能向下,不能向上。
调用时用<?>定义时用 <E>

泛型类的定义

1>类的静态方法和静态属性都不能使用泛型,因为泛型类是在创建对象的时候产生的。

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){
}
}


泛型与异常

类型参数在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();
}
}
}


泛型的一些局限型
1,catch不能使用泛型,在泛型集合中,不能用泛型创建对象,不允许使用泛型的对象。
2,不能实例化泛型
3,不能实例化泛型类型的数组
4,不能实例化泛型参数数
5,类的静态变量不能声明为类型参数类型

public class GenClass<T> {
private static T t; //编译错误
}


6,静态方法可以是泛型方法,但是不可以使用类的泛型。
7,泛型类不能继承自Throwable以及其子类
public GenExpection<T> extends Exception{}   //编译错误 
8,不能用于基础类型int等

Pair<double> //error
Pair<Double> //right

posted @ 2011-05-04 11:04  BuildNewApp  阅读(341)  评论(0编辑  收藏  举报