黑马程序员-java学习基础加强之泛型

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值