So I\'m working in Java and I want to declare a generic List.
So what I\'m doing so far is List
But no
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");
}
}
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.
You cannot add the "X"(String) into the list having type of directly so that you need to write a function which accept T as a parameter and add into the List, like
List<T> myList = new ArrayList<T>(0);
public void addValue(T t){
myList.add(t);
}
and while calling this function you can pass string.
object.addValue("X");