Let say i have a method: void write(List list) and i call this with
a List list,write(list) and trying to add in write() like
list.add(new Dog()) is a compilation error, why?
?
is a wildcard operator in generics, now what it means is that you don't exactly know what kind of List
you are getting. So how can you be sure that it can be a List
of Dog
s. If it was a List<Cat>
then your write
method would have added a Dog
to it. So Java restricts you from doing that.
Now, if i use bounded wild cards, write(List list> it
solves the above problem, why?
? super Dog
stands for any super class of Dog including itself. So when you get a List<? super Dog>
in write
you know that the List is a list of either List<Object> or List<Dog>
. In both cases it is safe to add a new Dog
to the list.