Reputation: 20571
How I can create genric List in Java? I also can pass Class<T>
instance to the method.
Like this:
public static <T> List<T> createList(Class<T> clazz) {
List<T> list = new ArrayList<T>();
list.add(clazz.newInstance());
return list;
}
Upvotes: 0
Views: 13328
Reputation: 1555
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
}
Upvotes: 0
Reputation: 12398
I don't understand why you want a method at all. You can just do new ArrayList<String>()
, new ArrayList<Integer>()
, etc.
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.
Upvotes: 5