Reputation: 703
Suppose I have:
class A{
}
class B extends A{
}
class C extends A{
}
Why and when we want to use ArrayList<? extends A>
, Why not simply write ArrayList<A>
?
Upvotes: 0
Views: 44
Reputation: 638
Consider that you are not the one creating the List, you are getting it passed to you from somewhere. Say you have a method that takes an argument List<? extends A>
. Someone could call your method and pass to you a List<B>
that he created. However, if you declared your argument to be just List<A>
, he would not be allowed to pass his List<B>
to you.
Here's why: In the first case, where your argument is List<? extends A>
, you are not allowed to add to this list because you don't know how the caller created it. If you added, say, an instance of C and returned, he would now have a C object in his List<B>
. If it were a real List<A>
, you'd be able to add to it safely.
Upvotes: 1