论坛首页 入门技术论坛

corejava辅导(16--4)

浏览 1009 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-12-03  

泛型方法的定义

 

把数组拷贝到集合时,数组的类型一定要和集合的泛型相同。

<...>定义泛型,其中的"..."一般用大写字母来代替,也就是泛型的命名,其实,在运行时会根据实际类型替换掉那个泛型。

 

需要泛型参数或返回值同时又是某个类的子类又是某个接口的实现类的时候,可以使用

<? extends Xxxx & Xxxx>这种写法,注意:接口类型要放在类的后面,且只能使用’&’符。

例:

public class Test{

<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>

 

泛型类的定义

 

我们也可以在定义类型中使用泛型

注意:静态方法中不能使用类的泛型,因为泛型类是在创建对象的时候给定泛型。

例:

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();

        }

    }

}

 

泛型的一些局限型

 

catch不能使用泛型,在泛型集合中,不能用泛型创建对象,不允许使用泛型的对象。

 

不能实例化泛型

 

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

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics