• Index

泛型的super通配符

Last updated: ... / Reads: 43 Edit

在 Java 中,泛型的super通配符用于限制传递给泛型类型参数的类型范围。它允许我们指定一个下界,表示只能接受某个类及其父类作为类型参数。例如,假设有一个泛型方法来处理列表List中的元素:

public static void processList(List<? super Integer> list) {
    // 处理列表中的元素
}

在这个例子中,使用了? super Integer语法来定义通配符,并通过super关键字将其限制为Integer或其父类。这意味着可以传递包含Integer类或其父类的列表给该方法。

以下是一些示例调用该方法的方式:

List<Number> numbers = new ArrayList<>();
processList(numbers);     // 正确,Number是Integer的父类

List<Object> objects = new ArrayList<>();
processList(objects);     // 正确,Object是Integer的父类

List<Integer> integers = new ArrayList<>();
processList(integers);    // 错误,Integer不是Integer的父类

通过使用super通配符,我们可以实现更灵活的泛型参数传递,允许传递具有特定类或其父类的列表,从而增加代码的可复用性和扩展性。


Comments

Make a comment

  • Index