25

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.

8
  • 1
    Have you tried passing it List<String> ? Commented Jan 16, 2013 at 9:44
  • See the documentation of the function that requires the List<T>, which will likely be a generic argument to the class it belongs to. You're likely the one defining what this T is somewhere in your own code. Commented Jan 16, 2013 at 9:45
  • T is not a concrete type, it is a generic type. can you paste the signature of "another function" ? Commented Jan 16, 2013 at 9:46
  • You can use List<Object> list = new ArrayList<Object>() , and after you get an element by get(int index) downcast it to the desire class which compatible to another function. Commented Jan 16, 2013 at 9:50
  • @AlvinWong: Please don't advise to use raw types. Commented Jan 16, 2013 at 9:51

3 Answers 3

28

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");
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Or a generic thingy in the method declaration like public <T extends SomeThing> T method(T arg) (though that might be a more complicated case then OP currently has).
@akaIDIOT yepp, i did include or generic method in my answer :)
1

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.

Comments

0

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.