Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using and declaring generic List<T>

So I'm working in Java and I want to declare a generic List.

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?

I've tried doing something like List.add("x") to see if I can add a string but that doesn't work.

(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.

like image 925
user1855952 Avatar asked Jan 16 '13 09:01

user1855952


People also ask

What does T stand for in generics?

< T > is a conventional letter that stands for "Type", and it refers to the concept of Generics in Java. You can use any letter, but you'll see that 'T' is widely preferred. WHAT DOES GENERIC MEAN? Generic is a way to parameterize a class, method, or interface.

How do you add to a generic list in Java?

You can get and insert the elements of a generic List like this: List<String> list = new ArrayList<String>; String string1 = "a string"; list. add(string1); String string2 = list. get(0);

How do you declare a generic type in Java?

To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class. As you can see, all occurrences of Object are replaced by T.


2 Answers

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");
    }
}
like image 157
PermGenError Avatar answered Sep 24 '22 05:09

PermGenError


The T is the type of the objects that your list will contain. You can write List<String> and use it in a function which needs List<T>, it shouldn't be a problem since the T is used to say that it can be anything.

like image 30
Cedias Avatar answered Sep 22 '22 05:09

Cedias