上边界限定通配符

利用 <? extends Fruit> 形式的通配符,可以实现泛型的向上转型:

//變數會是泛型的子類

public class GenericsAndCovariance {
    public static void main(String[] args) {
        // Wildcards allow covariance:
        List<? extends Fruit> flist = new ArrayList<Apple>();
        // Compile Error: can’t add any type of object:
        // flist.add(new Apple());
        // flist.add(new Fruit());
        // flist.add(new Object());
        flist.add(null); // Legal but uninteresting
        // We know that it returns at least Fruit:
        Fruit f = flist.get(0);
    }
}

 

下边界限定通配符

通配符的另一个方向是 “超类型的通配符“: ? super TT 是类型参数的下界。使用这种形式的通配符,我们就可以 ”传递对象” 了。还是用例子解释:

//變數會是泛型的父類

public class SuperTypeWildcards {
    static void writeTo(List<? super Apple> apples) {
        apples.add(new Apple());
        apples.add(new Jonathan());
        // apples.add(new Fruit()); // Error
    }
}
arrow
arrow
    全站熱搜

    學習程式 發表在 痞客邦 留言(0) 人氣()