问号(?)代表通配符,代表泛型中的未知类型,有时您可能想限制允许传递给参数的下限类型。
要声明一个下限的通配符参数,使用 “?”,然后使用super关键字,再列出其下限。
以下示例说明了如何使用super指定下界通配符。
package com.learnfk; import java.util.ArrayList; import java.util.List; public class GenericsTester { public static void addCat(List<? super Cat> catList) { catList.add(new RedCat()); System.out.println("Cat Added"); } public static void main(String[] args) { List<Animal> animalList= new ArrayList<Animal>(); List<Cat> catList= new ArrayList<Cat>(); List<RedCat> redCatList= new ArrayList<RedCat>(); List<Dog> dogList= new ArrayList<Dog>(); //add list of super class Animal of Cat class addCat(animalList); //add list of Cat class addCat(catList); //compile time error //can not add list of subclass RedCat of Cat class //addCat(redCatList); //compile time error //can not add list of subclass Dog of Superclass Animal of Cat class //addCat.addMethod(dogList); } } class Animal {} class Cat extends Animal {} class RedCat extends Cat {} class Dog extends Animal {}
这将产生以下输出-
Cat Added Cat Added
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
HarmonyOS快速入门与实战 -〔QCon+案例研习社〕