Possible Duplicate:
Java ArrayList of ? extends Interface
There is this code:
public static class B1 {}
public static class B2 extends B1 {}
public void fun() {
List<? extends B1> l3 = new ArrayList<>();
l3.add(new B2());
}
Compile error:
java: no suitable method found for add(Main.B2)
method java.util.List.add(int,capture#1 of ? extends Main.B1) is not applicable
(actual and formal argument lists differ in length)
method java.util.List.add(capture#1 of ? extends Main.B1) is not applicable
(actual argument Main.B2 cannot be converted to capture#1 of ? extends Main.B1 by method invocation conversion)
I guess that ? extends B1
means any type that extends from B1. It seems that type B2 extends from B1, so why object of this type cannot be added to the list and how to make it so that it can be added?
I guess that
? extends B1
means any type that extends from B1.
No. It means "a specific, but unknown, type that extends from B1". As the specific type is unknown, the compiler cannot enforce it, therefore operations like add
don't work.*
See the tutorial on wildcards.
how to make it so that it can be added?
Basically, don't use wildcards for this. You probably want this:
List<B1> l3 = new ArrayList<B1>();
null
(and a few other cases, see @Marko's comment below).
? extends B1
means: some type being or extending B1, but we don't know which one. So the list could be a List<B1>
, or a List<B2>
, or a List<B3>
(assuming B3 also extends B1). And you don't want to add a B2 to a List<B3>
, so the compiler forbids it.
You probably want a List<B1>
.
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