Let's say I have two classes A
and B
which extends A
. With the following method I can print a Collection
of A
or something extending A
:
private static void print(Collection<? extends A> collection) {
for (A element : collection) {
System.out.println(element);
}
}
It's great, I can do something like:
public static void main(String[] args) {
List<A> l1 = new ArrayList<>();
l1.add(new A());
l1.add(new B());
print(l1);
List<B> l2 = new ArrayList<>();
l2.add(new B());
l2.add(new B());
print(l2);
}
Now my question is why in my method main
(or somewhere else) I can write this
List<? extends A> l3 = new ArrayList<>();
but not this
l3.add(new A());
l3.add(new B());
I do understand why I can not add an instance of A
or B
in l3
. But why the first statement which seems useless is authorized ?
EDIT
I ask with another words because I think my question is misunderstood.
What can I do with my empty list List<? extends A> l3 = new ArrayList<>();
? I know it's not possible to add anything because the type of the list is unknown.
extends E means that it is also OK to add all members of a collection with elements of any type that is a subtype of E.
extends Number> represents a list of Number or its sub-types such as Integer and Double. Lower Bounded Wildcards: List<? super Integer> represents a list of Integer or its super-types Number and Object.
extends Object> is a bounded wildcard (an unknown that extends Object , whereas <E extends Object> is type bounded ( E requires a Parameterized type that extends Object ).
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.
List<? extends A> l3
means that l3
might be a List<A>
or it might be a List<B>
. <? extends A>
means the compiler doesn't know and cannot safely assume any more than that.
Since it might be List<B>
, l3.add(new A())
is not safe. The List would be corrupt, since it would not truly contain only instances of B.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With