JAVA泛型

(github地址: https://github.com/liufeiSAP/javaStudy)
泛型类:
publicclassBox<T> {
    // T stands for "Type"
    privateT t;
    publicvoidset(T t) { this.t = t; }
    publicT get() { returnt; }
}
Box<Integer> integerBox = newBox<Integer>();
Box<Double> doubleBox = newBox<Double>();
Box<String> stringBox = newBox<String>();
泛型方法:
声明一个泛型方法很简单,只要在返回类型前面加上一个类似 <T> 或者<K, V>的形式:
限定符:
查找一个泛型数组中大于某个特定元素的个数:
错误写法:
publicstatic<T> intcountGreaterThan(T[] anArray, T elem) {
    intcount = 0;
    for(T e : anArray)
        if(e > elem)  // compiler error, 不能保证任意类型都是可以比较的。
            ++count;
    returncount;
}
正确写法:
做一个类似于下面这样的声明,这样就等于告诉编译器类型参数T代表的都是实现了Comparable接口的类,这样等于告诉编译器它们都至少实现了compareTo方法。
publicstatic<T extendsComparable<T>> intcountGreaterThan(T[] anArray, T elem) {
    intcount = 0;
    for(T e : anArray)
        if(e.compareTo(elem) > 0)
            ++count;
    returncount;
}
注意: 这里可以参考String的定义:
public final class String implements Serializable, Comparable<String>, CharSequence
通配符:
有如下函数定义:   publicvoidboxTest(Box<Number> n) { /* ... */}
那么现在Box<Number> n允许接受什么类型的参数?我们是否能够传入Box<Integer>或者Box<Double>呢?答案是否定的,虽然Integer和Double是Number的子类,但是在泛型中Box<Integer>或者Box<Double>与Box<Number>之间并没有任何的关系。
错误示例:
classFruit {}
classApple extendsFruit {}
classOrange extendsFruit {}
publicclassGenericReading {
    staticList<Apple> apples = Arrays.asList(newApple());
    staticList<Fruit> fruit = Arrays.asList(newFruit());
    staticclassReader<T> {
        T readExact(List<T> list) {
            returnlist.get(0);
        }
    }
    staticvoidf1() {
        Reader<Fruit> fruitReader = newReader<Fruit>();
        // Errors: List<Fruit> cannot be applied to List<Apple>.
        // Fruit f = fruitReader.readExact(apples);   相当于实参是List<apple>,而形参是List<frut>, 两者没有联系,虽然apple是frut的子类
    }
    publicstaticvoidmain(String[] args) {
        f1();
    }
}
正确示例:
staticclassCovariantReader<T> {
    T readCovariant(List<? extendsT> list) {   // 用通配符来解决这个问题
        returnlist.get(0);
    }
}
staticvoidf2() {
    CovariantReader<Fruit> fruitReader = newCovariantReader<Fruit>();
    Fruit f = fruitReader.readCovariant(fruit);
    Fruit a = fruitReader.readCovariant(apples);
}
publicstaticvoidmain(String[] args) {
    f2();
}
这样就相当与告诉编译器, fruitReader的readCovariant方法接受的参数只要是满足Fruit的子类就行(包括Fruit自身),这样子类和父类之间的关系也就关联上了。
PECS原则:
      问题: 上面可以取元素,是否可以往List中add元素。    List<? extendsFruit> flist = newArrayList<Apple>();
       答案是否定,Java编译器不允许我们这样做,为什么呢?对于这个问题我们不妨从编译器的角度去考虑。因为List<? extends Fruit> flist它自身可以有多种含义:
1 2 3  | 
 
 
  | 
- 当我们尝试add一个Apple的时候,flist可能指向
new ArrayList<Orange>(); - 当我们尝试add一个Orange的时候,flist可能指向
new ArrayList<Apple>(); - 当我们尝试add一个Fruit的时候,这个Fruit可以是任何类型的Fruit,而flist可能只想某种特定类型的Fruit,编译器无法识别所以会报错。
 
      所以对于实现了<? extends T>的集合类只能将它视为Producer向外提供(get)元素,而不能作为Consumer来对外获取(add)元素。
       如果我们要add元素应该怎么做呢?可以使用<? super T>:
   publicclassGenericWriting {
    staticList<Apple> apples = newArrayList<Apple>();
    staticList<Fruit> fruit = newArrayList<Fruit>();
    static<T> voidwriteExact(List<T> list, T item) {
        list.add(item);
    }
    staticvoidf1() {
        writeExact(apples, newApple());
        writeExact(fruit, newApple());
    }
    static<T> voidwriteWithWildcard(List<? superT> list, T item) {
        list.add(item)
    }
    staticvoidf2() {
        writeWithWildcard(apples, newApple());
        writeWithWildcard(fruit, newApple());
    }
    publicstaticvoidmain(String[] args) {
        f1(); f2();
    }
}
注意: <? extends T> 和 <? super T> 一般只作为函数的形参使用。一定要弄明白两者谁可以get, 谁可以add. 规律是: ”Producer Extends, Consumer Super”:
- “Producer Extends” – 如果你需要一个只读List,用它来produce T,那么使用
? extends T。 - “Consumer Super” – 如果你需要一个只写List,用它来consume T,那么使用
? super T。 - 如果需要同时读取以及写入,那么我们就不能使用通配符了。
 
如何阅读过一些Java集合类的源码,可以发现通常我们会将两者结合起来一起用,比如像下面这样:
publicclassCollections {
    publicstatic<T> voidcopy(List<? superT> dest, List<? extendsT> src) {
        for(inti=0; i<src.size(); i++)
            dest.set(i, src.get(i));
    }
}
类型擦除导致的问题:Java泛型很大程度上只能提供静态类型检查,然后类型的信息就会被擦除
(1):在Java中不允许创建泛型数组,类似下面这样的做法编译器会报错:
1  | 
  | 
也就是说下面的这个例子是不可以的:
    List<String>[] ls = new ArrayList<String>[10];  而使用通配符创建泛型数组是可以的,如下面这个例子:
List<?>[] ls = new ArrayList<?>[10];这样也是可以的:List<String>[] ls = new ArrayList[10];
        (2):我们无法对泛型代码直接使用instanceof关键字
最后: 通配符是为了解决,在函数传参的时候, “虽然Number和Integer是继承关系,但是 List<Number> 和 List<Integer> 没有关系” 这个问题而提出的,
并且可以定义通配符的数组(单是不能定义泛型数组)。
补充: <T> 和 <?> 的区别:
https://www.zhihu.com/question/31429113
类型参数“<T>”主要用于声明泛型类或泛型方法。 无界通配符“<?>”主要用于使用泛型类或泛型方法。
List<?> cc = new ArrayList<String>();
cc.add("fd"); // 编译有错误
实际更常用的是<? extends XXX>或者<? super XXX>两种,带有上下界的通配符
以上是 JAVA泛型 的全部内容, 来源链接: utcz.com/z/391551.html

