简体   繁体   中英

Java | Adding items to List<?>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM