使用并宣布泛型列表&LT; T&GT; [英] Using and declaring generic List<T>
问题描述
所以我在Java中工作,我要声明一个泛型列表。
So I'm working in Java and I want to declare a generic List.
所以我在做什么,到目前为止是列表&LT; T&GT;名单=新的ArrayList&LT; T&GT;();
So what I'm doing so far is List<T> list = new ArrayList<T>();
但现在我想在一个元素添加。我怎么做?什么是一个通用的元素是什么样子?
But now I want to add in an element. How do I do that? What does a generic element look like?
我试着做一些像List.add(X),看看是否我可以添加一个字符串,但不起作用。
I've tried doing something like List.add("x") to see if I can add a string but that doesn't work.
(我不声明列表与LT的原因;串&GT;
是因为我有这个名单传递到另一个函数,只需要名单,LT ; T&GT;
作为参数
(The reason I'm not declaring a List<String>
is because I have to pass this List into another function that only takes List<T>
as an argument.
推荐答案
您应该要么像下面一个泛型类或泛型方法:
You should either have a generic class or a generic method like below:
public class Test<T> {
List<T> list = new ArrayList<T>();
public Test(){
}
public void populate(T t){
list.add(t);
}
public static void main(String[] args) {
new Test<String>().populate("abc");
}
}
这篇关于使用并宣布泛型列表&LT; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!