Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding data to generic ? extends list [duplicate]

Tags:

java

generics

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?

like image 224
scdmb Avatar asked Jan 06 '13 12:01

scdmb


2 Answers

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>();


* Well, they do work, but only for null (and a few other cases, see @Marko's comment below).
like image 149
Oliver Charlesworth Avatar answered Oct 16 '22 18:10

Oliver Charlesworth


? 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>.

like image 2
JB Nizet Avatar answered Oct 16 '22 18:10

JB Nizet