Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of List<?> if one can only insert a null value?

Based on the information provided in the link, it says that:

It's important to note that List<Object> and List<?> are not the same. You can insert an Object, or any subtype of Object, into a List<Object>. But you can only insert null into a List<?>.

What is the use of using List<?> when only null can be inserted?

For example,

methodOne(ArrayList<?> l): We can use this method for ArrayList of any type but within the method we can’t add anything to the List except null.

l.add(null);//(valid)
l.add("A");//(invalid)
like image 336
kittu Avatar asked Mar 30 '15 09:03

kittu


1 Answers

You use the unbounded wildcards when the list (or the collection) is of unknown types.

Like the tutorial says, it's used when you want to get information about some list, like printing its content, but you don't know what type it might be containing:

public static void printList(List<?> list) {
    for (Object elem: list)
        System.out.print(elem + " ");
    System.out.println();
}

You shouldn't use it when you want to insert values to the list, since the only value allowed is null, because you don't know what values it contains..

like image 188
Maroun Avatar answered Oct 21 '22 16:10

Maroun