What is the purpose of a List <?> If you can only insert a null value?

Based on the information provided in the link , it is said that:

It is important to note that List<Object> and List<?> Do not match. You can insert an object or any subtype of an object into a List<Object> . But you can only embed null in List<?> .

What is the use of using List<?> When you can only insert null ?

For instance,

methodOne(ArrayList<?> l): We can use this method for an ArrayList any type, but inside a method that we cannot add to the list except null .

 l.add(null);//(valid) l.add("A");//(invalid) 
+5
source share
2 answers

You use unlimited wildcards when a list (or collection) has unknown types.

As the textbook says, it is used when you want to get information about a list, for example, print its contents, but you don’t know what type it may contain:

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

You should not use it if you want to insert values ​​into the list, because the valid value is null , because you do not know what values ​​it contains.

+11
source

You can get items from the list.

List<?> usually used as a type for a list of unknown types of objects returned by a method or the way where you read items, rather than adding them.

+4
source

Source: https://habr.com/ru/post/1216444/


All Articles