Java 泛型 - 下界通配符


问号(?),代表通配符,代表泛型中的未知类型。有时您可能想要限制允许传递给类型参数的类型种类。例如,对数字进行操作的方法可能只想接受 Integer 或其超类(如 Number)的实例。

要声明下限通配符参数,请列出 ?,后跟 super 关键字,然后是其下限。

例子

以下示例说明了如何使用 super 来指定下限通配符。

package com.tutorialspoint;

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