问号(?)代表通配符,代表泛型中的未知类型.有时您可能希望限制允许传递给类型参数的类型.例如,对数字进行操作的方法可能只想接受Integer或其超类(如Number)的实例.
要声明一个较低的有界Wildcard参数,列出?,然后是超级关键字,后跟其下限.
示例
以下示例说明了如何使用super来指定下限通配符.
package com.it1352; 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) { ListanimalList= new ArrayList (); List catList= new ArrayList (); List redCatList= new ArrayList (); List dogList= new ArrayList (); //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 AddedCat Added