zoukankan      html  css  js  c++  java
  • Java中<?>,<? extends E>,<? super E>

      在集合中,经常可看到<?>,<? extends E>,<? super E>,它们都是属于泛型;

      <?>:

       是泛型通配符,任意类型,如果没有明确,那么就是Object以及任意类型的Java类;

      

      <? extends E>:

       向下限定,E及其子类,表示包括E在内的任何子类;

      <? super E>:

       向上限定,E及其父类,表示包括E在内的任何父类;

      示例如下:

    class Animal {}
    
    class Dog extends Animal {}
    
    class Cat extends Animal {}
    
    public class CollectionDemo {
    
            public static void main(String[] args) {
                Collection<?> c1 = new ArrayList<Animal>();
                Collection<?> c2 = new ArrayList<Dog>();
                Collection<?> c3 = new ArrayList<Cat>();
                Collection<?> c4 = new ArrayList<Object>();
    
                Collection<? extends Animal> c5 = new ArrayList<Animal>();
                Collection<? extends Animal> c6 = new ArrayList<Dog>();
                Collection<? extends Animal> c7 = new ArrayList<Cat>();
                // Collection<? extends Animal> c8 = new ArrayList<Object>();
    
                Collection<? super Animal> c9 = new ArrayList<Animal>();
                // Collection<? super Animal> c10 = new ArrayList<Dog>();
                // Collection<? super Animal> c11 = new ArrayList<Cat>();
                Collection<? super Animal> c12 = new ArrayList<Object>();
            }
    
    }
    

        在上述代码中,c1,c2,c3,c4中<?>代表任意类型,c5,c6,c7中<? extends Animal>代表包括Animal在内的任何子类;而c8中,Object是所有类的基类,Animal是它的子类,<? extends Animal>只包含Animal及其子类,所以这里会编译报错;c9,c10,c11,c12中<? super Animal>表示包含Animal及其父类,c10,c11这里会编译报错;

  • 相关阅读:
    Linux tcpdump命令详解
    移动开发网站收集
    Struts+2权威指南基于WebWork核心的MVC开发源码下载
    Eclipse+php插件+Xdebug搭建PHP完美开发/调试环境指南
    java相对目录和绝对目录解析
    python学习网站搜集
    window下开发iphone程序环境搭建iphone tool chain
    Windows下编译objectiveC
    java class路径获取
    完全优化MySQL数据库性能的八个方法
  • 原文地址:https://www.cnblogs.com/coder-zyc/p/10387625.html
Copyright © 2011-2022 走看看