zoukankan      html  css  js  c++  java
  • Java重温学习笔记,泛型通配符

    一、常用的 T,E,K,V,?,通常情况下,是这样约定的(非必须):

    • ?表示不确定的 java 类型
    • T (type) 表示具体的一个java类型
    • K V (key value) 分别代表java键值中的Key Value
    • E (element) 代表Elem

    二、无边界通配符?,看下面的代码:

    import java.util.*;
    
    public class MyDemo {
        public static void printList(List<?> list) {
            for (Object o : list) {
                System.out.println(o);
            }
        }
    
        public static void main(String[] args) {
            List<String> l1 = new ArrayList<>();
            l1.add("aa");
            l1.add("bb");
            l1.add("cc");
            printList(l1);
            List<Integer> l2 = new ArrayList<>();
            l2.add(11);
            l2.add(22);
            l2.add(33);
            printList(l2);
        }
    }

    二、上界通配符 < ? extends E>,看下面的代码:

    import java.util.*;
    
    public class MyDemo {
        class Animal{
            public int countLegs(){
                return 3;
            }
        }
        
        class Dog extends Animal{
            @Override
            public int countLegs(){
                return 4;
            }
        }
        
        // 限定上界,但是不关心具体类型是什么,对于传入的 Animal 的所有子类都支持
        static int countLegs (List<? extends Animal > animals ) {
            int retVal = 0;
            for ( Animal animal : animals ) {
                retVal += animal.countLegs();
            }
            return retVal;
        }
        
        // 这段代码就不行,编译时如果实参是Dog则会报错。
        static int countLegs1 (List< Animal > animals ) {
            int retVal = 0;
            for ( Animal animal : animals ) {
                retVal += animal.countLegs();
            }
            return retVal;
        }
    
        public static void main(String[] args) {
            List<Dog> dogs = new ArrayList<>();
             // 不会报错
            System.out.println(countLegs(dogs));
            // 报错
    //        countLegs1(dogs);
        }
    }

    三、下界通配符 < ? super E>,用 super 进行声明,表示参数化的类型可能是所指定的类型,或者是此类型的父类型,直至 Object。代码就不示范了。

    文章参考:

    https://www.cnblogs.com/minikobe/p/11547220.html

  • 相关阅读:
    eclipse里面已经提交的svn提交
    session 失效
    svn版本管理
    前端控制台调试经验
    python001环境搭建及入门 http://python.jobbole.com/81332/
    eclipse自己写makefile 建工程
    编码风格
    算法导论第22章22.2广度优先搜索
    vnc相关
    eclipse相关设置
  • 原文地址:https://www.cnblogs.com/nayitian/p/14904575.html
Copyright © 2011-2022 走看看