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;
}
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;
}
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.
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
}