Groovy - 泛型
在定义类、接口和方法时,泛型使类型(类和接口)成为参数。 就像在方法声明中使用的更熟悉的形式参数一样,类型参数为您提供了一种通过不同输入重用相同代码的方法。 区别在于形式参数的输入是值,而类型参数的输入是类型。
集合的泛型
集合类(如 List 类)可以通用化,以便在应用程序中只接受该类型的集合。 广义 ArrayList 的示例如下所示。 以下语句的作用是它只接受字符串类型的列表项 −
List<String> list = new ArrayList<String>();
在下面的代码示例中,我们正在执行以下操作 −
- 创建一个只包含字符串的通用 ArrayList 集合。
- 将 3 个字符串添加到列表中。
- 对于列表中的每个项目,打印字符串的值。
class Example {
static void main(String[] args) {
// 创建通用列表集合
ListType<String> lststr = new ListType<>();
lststr.set("First String");
println(lststr.get());
ListType<Integer> lstint = new ListType<>();
lstint.set(1);
println(lstint.get());
}
}
public class ListType<T> {
private T localt;
public T get() {
return this.localt;
}
public void set(T plocal) {
this.localt = plocal;
}
}
上述程序的输出将是 −
First String 1

