In my last question (thank you all that answer me), I have learnt the difference between List<Object>
and List<?>
.
However I still can't see the usefulness of wildcards.
I have two ArrayList
s:
ArrayList<Integer> li = new ArrayList<Integer>(Arrays.asList(1,2,3));
ArrayList<String> ls = new ArrayList<String>(Arrays.asList("one","two","three"));
Now, look at the two blocks of code below:
static void printList(ArrayList<?> list)
{
for (Object elem: list)
System.out.print(elem + " ");
System.out.println();
}
and
static <T> void printList(ArrayList<T> list)
{
for (T elem: list)
System.out.print(elem + " ");
System.out.println();
}
When I call:
printList(li);
printList(ls);
Both methods return the output:
1 2 3
one two three
However the second solution, in the for loop, instead of Object
s I use parametrized types (much more elegant I think).
So, the main question remains: Why do we need wildcards?