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

  • 相关阅读:
    netlink(todo)
    【拓展】如何画好架构图
    【JS】527- 关于 JS 中的浮点计算
    【CSS】526- CSS 控制图标颜色
    【拓展】一个故事讲完CPU的工作原理
    【面试题】525- 阿里 P6 的面经
    【生活】你在第几楼?80后、90后扎心图鉴
    【JS】524- 三分钟迁移 Ant Design 4
    【Web技术】522- 设计体系的响应式设计
    【适配】521- 移动端开发各种兼容适配问题(屏幕、图像、字体与布局等)
  • 原文地址:https://www.cnblogs.com/nayitian/p/14904575.html
Copyright © 2011-2022 走看看