Following is an example of Generics with wild card
public static void printListItems(List<object> list) {
for (Object listItem : list)
System.out.println(listItem);
}
In this example we want to print list items of any type but it can’t print List<Integer>
, List<String>
etc. because they are not subtypes of List<Object>
. This problem can be solved using unbounded wildcard.
public static void printListItems(List<?> list) {
for (Object listItem : list)
System.out.println(listItem);
}
I read this above code in Java tutorial. For the first example , it says it cannot work because List<String>
is not sublass of List<Object>
.
Then why it is so that in the second example the for loop is working with taking listItem as dataType of Object
and iterating through List<String>
elements.