java 创建通用列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15518013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create generic List
提问by MyTitle
How I can create genric List in Java? I also can pass Class<T>
instance to the method.
如何在 Java 中创建通用列表?我也可以将Class<T>
实例传递给方法。
Like this:
像这样:
public static <T> List<T> createList(Class<T> clazz) {
List<T> list = new ArrayList<T>();
list.add(clazz.newInstance());
return list;
}
回答by Javier
I don't understand why you want a method at all. You can just do new ArrayList<String>()
, new ArrayList<Integer>()
, etc.
我不明白你为什么想要一种方法。你可以做new ArrayList<String>()
,new ArrayList<Integer>()
等等。
If you want to write it as a method, do
如果要将其编写为方法,请执行
public static <T> List<T> createList() {
return new ArrayList<T>();
}
The return type List<T>
is inferred by the compiler.
返回类型List<T>
由编译器推断。
回答by Mr.Cool
if you want to pass the instance to list means you can try this
如果你想将实例传递给列表意味着你可以试试这个
public class info {
private int Id;
public void setId(int i_Id) {
this.Id = i_Id;
}
public int getId() {
return this.Id;
}
}
class two{
private List<info> userinfolist;
userinfolist= new ArrayList<info>();
//now you can add a data by creating object to that class
info objinfo= new info();
objinfo.setId(10);
userinfolist.add(objinfo); .//add that object to your list
}