zoukankan      html  css  js  c++  java
  • 读书笔记-泛型有限通配符

    发送一个子类对象给声明了其父类类型的方法,是没问题的;

    但是发送一个子类对象List给声明了其父类类型List的方法,是不行的;

    这个时候,有限通配符就可以派上用场,在接受方法的声明中:List<? extends E> o;

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    {      
      Stack<One> stack = new Stack<One>();
    
      stack.pushSingle(new One());
    
      stack.pushSingle(new Two());
    
      List<One> arrayList = new ArrayList<One>();
    
      stack.push(arrayList);
    
      //有限通配符的用法
    
      List<Two> list = new ArrayList<Two>();
    
      stack.push(list); //The method push(List<One>) in the type Stack<One> is not applicable for the arguments (List<Two>)
    
      stack.push2(list);
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    
    class Stack<E> {
    
    public void pushSingle(E o) {
    
    }
    
    public void push(List<E> o) {
    
    }
    
    public void push2(List<? extends E> o) {
    
    }
    
    }
    
    class One {
    
    }
    
    class Two extends One {
    
    }
  • 相关阅读:
    软工实践
    福大软工 · 最终作业
    福大软工 · 第十二次作业
    Beta冲刺(7/7)
    Beta冲刺(5/7)
    Beta 冲刺(6/7)
    Beta冲刺 (4/7)
    Beta冲刺 (3/7)
    Beta冲刺 (2/7)
    Beta 冲刺(1/7)
  • 原文地址:https://www.cnblogs.com/mosthink/p/5288847.html
Copyright © 2011-2022 走看看