关于泛型的一些问题

来源:互联网 发布:win764位精简优化版 编辑:程序博客网 时间:2024/05/15 08:02

一、泛型在任何运行时需要知道确切类型信息的操作都将无法工作

package generics;//: generics/Erased.java// {CompileTimeError} (Won't compile)public class Erased<T> {  private final int SIZE = 100;  public static void f(Object arg) {    if(arg instanceof T) {}          // Error    T var = new T();                 // Error    T[] array = new T[SIZE];         // Error    T[] array = (T)new Object[SIZE]; // Unchecked warning  }} ///:~

二、泛型类型参数在声明什么类型就必须实例化什么类型,类型继承和多态不能用于泛型类型参数。

class Fruit {}class Apple extends Fruit {}class Orange extends Fruit {}public class NonCovariantGenerics {  // Compile Error: incompatible types:  List<Fruit> flist = new ArrayList<Apple>();} ///:~
在实例化一个List的时候 指定一个泛型类型,如果这个类型是Fruit,那么就代表后面所有继承Fruit的子类都可以添加到当前的集合中;但是在赋值的时候却是使用的 Apple,那么这个ArrayList 中的泛型定义就是 Apple类型,也就意味着后面对 这个 ArrayList 进行Add等操作都必须是Apple类型或者是Apple的子类;也就和前面的Fruit以及Fruit的子类自相矛盾了;所以不允许这样进行擦除。

三、List<? extends T> 这里的T可以是任何类或者接口,?可以是T代表的这个类本身或子类;List<? super T>这里?可以是T代表的这个类本身或它的父类;

四、泛型对象的泛型参数类型在声明的时候确定

Holder<?> unbounded = new Holder<Long>();

这里unbounded的泛型类型参数是未知的;因为进行了泛型转型 擦除掉了

五、泛型类对象做参数,使用方法的时候,传递的对象的泛型参数必须一致

package generics;public class Wildcards {    static <T> T wildSubtype(Holder<? extends T> holder, T arg) {    T t = holder.get();    return t;  }  static <T> void wildSupertype(Holder<? super T> holder, T arg) {    holder.set(arg);    Object obj = holder.get();  }  public static void main(String[] args) {    Holder<Long> qualified = new Holder<Long>();    Holder<?> unbounded = new Holder<Long>();    Holder<? extends Long> bounded = new Holder<Long>();    Long lng = 1L;    Long r10 = wildSubtype(qualified, lng);    // OK, but can only return Object:    Object r11 = wildSubtype(unbounded, lng);//Error    Long r12 = wildSubtype(bounded, lng);    wildSupertype(qualified, lng);     wildSupertype(unbounded, lng); // Error:    //   wildSupertype(Holder<? super T>,T) cannot be    //   applied to (Holder<capture of ?>,Long)     wildSupertype(bounded, lng); // Error:    //   wildSupertype(Holder<? super T>,T) cannot be    //  applied to (Holder<capture of ? extends Long>,Long)  }} ///:~

 Object r11 = wildSubtype(unbounded, lng);//Error
wildSupertype(unbounded, lng); // Error:
wildSupertype(bounded, lng); // Error:
这三句话都是因为参数的泛型参数类型不对出错。


Long r12 = wildSubtype(bounded, lng);
这句没出错,说明参数可以为参数类型不确定的泛型。


0 0
原创粉丝点击