extends(上界)、super(下界)在泛型中的使用,并非如其意

    1,在类的定义中, 可以直接使用T的方法
    <? super Type> 无法在类的声明处使用

    1. public class HasF {
    2. public void f(){
    3. System.out.println("HasF.f() ");
    4. }
    5. }
    6. class Manipulator<T>{ class Manipulator<T extends HasF>{
    7. private T o; .......
    8. public Manipulator(T o){
    9. this.o = o;
    10. }
    11. public void manipulate(){
    12. //o.f(); T没有限定边界
    13. }
    14. } }

    2,实例声明中, <? extends Type> 无法使用任何带有泛型的方法
    <? super Type> 可以使用任意的方法

    1. class Fruit{}
    2. class Apple extends Fruit{}
    3. class Jonathan extends Apple{}
    4. class Orange extends Fruit{}
    5. public class CovarianArrays {
    6. public static void main(String[] args) {
    7. //使用Arrays.asList 可以对extList 进行初始化
    8. List<? extends Fruit> extList = new ArrayList<Fruit>();
    9. //extList.add(new Apple());
    10. //extList.add(new Fruit());
    11. extList.contains(new Apple());
    12. List<? super Fruit> supList = new ArrayList<Fruit>();
    13. supList.add(new Apple());
    14. supList.add(new Fruit());
    15. System.out.println(supList.contains(new Apple()));
    16. }
    17. }

    3,方法参数中同2

    1. public static void writeTo(List<? super Apple> apples){
    2. apples.add(new Apple());
    3. apples.add(new Jonathan());
    4. //apples.add(new Fruit());
    5. }
    6. public static void writeTo2(List<? extends Apple> apples){
    7. //apples.add(new Apple());
    8. //apples.add(new Jonathan());
    9. apples.contains(new Apple());
    10. apples.get(0);
    11. }