Based on the information provided in the link, it says that:
It's important to note that
List<Object>
andList<?>
are not the same. You can insert an Object, or any subtype of Object, into aList<Object>
. But you can only insert null into aList<?>
.
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)
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With