0

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;
}
WelcomeTo
  • 19,843
  • 53
  • 170
  • 286

2 Answers2

5

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.

Javier
  • 12,100
  • 5
  • 46
  • 57
  • But does it work? I think I can't create `new ArrayList`. But even if I can do it, according to this answer http://stackoverflow.com/a/5662447/921193 I can't add to it elements – WelcomeTo Mar 20 '13 at 07:57
  • If you do it outside the method, you will need to use the right type argument (`new ArrayList()`, etc). In the method, it is a different story, because `T` is a type parameter. The method creates a generic list of *some type*. The actual type doesn't matter (because of type erasure: the runtime type of `ArrayList` is the same as the runtime type of `ArrayList`). What you cannot do is add things to a `List>`, but we are not doing that in this case: `List list =createList()` – Javier Mar 20 '13 at 08:07
0

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
     }
Mr.Cool
  • 1,525
  • 10
  • 32
  • 51