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

3

8

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)
Cordwain answered 30/3, 2015 at 9:0 Comment(0)
G
13

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..

Grani answered 30/3, 2015 at 9:6 Comment(0)
N
5

You can get elements from your list.

List<?> is usually used as a type for a list of unknown-typed objects returned by a method or so, where you read elements from, rather than adding them.

Nogging answered 30/3, 2015 at 9:4 Comment(0)
E
1

List<?> is quite different. If we try and add objects into a List<?>, even if the object is of type Object, we can't do it. It says,

add(capture<?>) in java.util.List cannot be applied to (java.lang.Object)

Now that might seem a bit restrictive. If you can't have any values being passed as parameters, which is what I mean when I say put into a list, then, what can you do with it?

Well, let's see why that restriction exists. To begin with, we know that arrays are covariant. So what that means is we could take an array of Strings and put that into an Object Array.

Array of Strings to Object

So here, if we take that first object and we assign it to a random String, everything will be fine. And if we assign it to a new Object, if we add that in, then we will get an ArrayStoreException

Exception in thread "main" java.lang.ArrayStoreException: java.lang.Object

because of the unsafety of covariant arrays.

Well, in the case of List<?>, what the Java compiler is trying to do for us by banning us from adding values into a List<?> or a List<? extends Object> is put us into a position where this type can only be safely used. And in fact, the only value that you are allowed to put into a List<?> is the null value because null can be coerced into any type.

Esmerolda answered 7/11, 2021 at 5:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.