1

I am wanting to take user data in one method and pass that data to an "add" method, as to add said data to a generic arraylist. However I receive the following error message...

add (T) in List cannot be applied to (java.lang.String)

I'm not sure if this is a static problem or not...

My simplified code:

List<T> list = new ArrayList<T>();

void dataCollection() {
    Scanner scan = new Scanner(System.in);
    System.out.println("type data");
    add(scan.next());
}

void add(T t) {
    list.add(t);
}

1 Answer 1

1

If you want to add Strings to your List, define it as a List<String>, not List<T>.

A List<T> might be (depending on how your class is instantiated), for example, a List<Integer>, which can't hold Strings.

If you truly need your List to be generic, you shouldn't be adding Strings to it.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the advice Eran. This is a first adventure into generics for me, so I'm still learning!

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.