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

原文地址:https://www.cnblogs.com/nayitian/p/14904575.html