3

I googled around and I couldn't really understand how to do this. I'm trying to add items to a list like this: List<?>. My code looks something like this:

public class Test {
    private List<?> list;

    public Test(List<?> useThisList) {
        this.list = useThisList;
    }

    public void add(Object add) {
        this.list.add(add); // this won't compile
    }
}

However, as commented, that code won't compile. I've tried to change it to something like:

public void add(? add) {
    this.list.add(add);
}

But that won't compile for more obvious reasons. Does anyone know what I need to change this to to make it function properly? Thanks in advance!

By the way, when it does work, you should be able to do this:

List<String> list = new ArrayList<String>();
new Test(list).add("hello");
2
  • 2
    Well if you don't know the kind of list you've got, how do you know you can add add to it? Perhaps your Test class should be generic... Commented Jan 17, 2016 at 14:53
  • I would encourage you to read effective java 2nd edition By Joshua Blochs and refer to the item about generics. It gives a handful of insights on how to do a good use of generics / wildcarss Commented Jan 17, 2016 at 15:15

1 Answer 1

5

Make your Test class generic

public class Test<E> {
    private List<E> list;

    public Test(List<E> useThisList) {
        this.list = useThisList;
    }

    public void add(E add) {
        this.list.add(add); // this will compile
    }
}

Instantiate your test class like this

Test<String> t = new Test<String>(new ArrayList<String>());
t.add("Something");
Sign up to request clarification or add additional context in comments.

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.