泛型

1.泛型方法

public static <T> void method(T t){}
public static <T>  T method(T t){
    return (T)new Object();
}
public static  <E extends Person> void method2(E e){
    System.out.println(e.getName());
}

2.泛型类

public class Test<T> {
    public T data;
}
public class PersonOpert implements GenericInterface<Person, User> {
    @Override
    public int add(Person t) {
        return 0;
    }
    @Override
    public int edit(Person t, User e) {
        return 0;
    }
    @Override
    public Person get(Integer id) {
        return null;
    }
    @Override
    public int delete(Integer id) {
        return 0;
    }
}

3.泛型接口

interface Operator<T>{
    void add(T t);
}
public interface GenericInterface<T, E> {
    public  int add(T t);
    public  int edit(T t, E e);
    public  T  get(Integer id);
    public int delete(Integer id);
}

4. 泛型的一些规则和限制
* 泛型的类型参数只能是类类型(包括自定义类),不能是基本数据类型。
* 泛型的类型参数可以有多个。
* 泛型的参数类型可以使用extends语句,例如<T extends superclass>。习惯上称为“有界类型”。
* 泛型的参数类型还可以是通配符类型。

5.? 通配符类型
* <? extends T> 表示类型的上界,表示参数化类型的可能是T 或是 T的子类
* <? super T> 表示类型下界(Java Core中叫超类型限定),表示参数化类型是此类型的超类型(父类型),直至Object
* List<? extends Fruit> flist = new ArrayList<Apple>(); 
* List<? extends Fruit> 表示 “具有任何从Fruit继承类型的列表”,编译器无法确定List所持有的类型,所以无法安全的向其中添加对象。可以添加null,因为null 可以表示任何类型。所以List 的add 方法不能添加任何有意义的元素,但是可以接受现有的子类型List<Apple> 赋值。
* List<? super Fruit> 表示“具有任何Fruit超类型的列表”,列表的类型至少是一个 Fruit 类型,因此可以安全的向其中添加Fruit 及其子类型。由于List<? super Fruit>中的类型可能是任何Fruit 的超类型,无法赋值为Fruit的子类型Apple的List<Apple>.

6.泛型的作用

泛型提供了编译期的类型安全,确保你只能把正确类型的对象放入JavaSE中,避免了在运行时出现ClassCastException。

posted @ 2016-02-16 19:21  嘉禾世兴  阅读(226)  评论(0编辑  收藏  举报