0

I write some code like this:

public class Generic {
    interface Base {}

    static class Derived implements Base {

    }

    public static void main(String args[]) {
        List<? extends Base> list = new ArrayList<>();
        list.add(new Derived());//line 16
    }
}

And the error:

Error:(16, 13) java: no suitable method found for add(Generic.Derived)
    method java.util.Collection.add(capture#1 of ? extends Generic.Base) is not applicable
      (argument mismatch; Generic.Derived cannot be converted to capture#1 of ? extends Generic.Base)
    method java.util.List.add(capture#1 of ? extends Generic.Base) is not applicable
      (argument mismatch; Generic.Derived cannot be converted to capture#1 of ? extends Generic.Base)
Sayakiss
  • 6,878
  • 8
  • 61
  • 107
  • 1
    Remove `? extends ` and it'll work. – Andreas Dec 03 '15 at 07:31
  • My question is, as far as I know, `Derived` extends `Base`, but why I can't put it to the list? – Sayakiss Dec 03 '15 at 07:33
  • @Sayakiss -Because `Collection extends Type>` acts like a producer (from the collections pov), you can't add stuff to it. `? extends Type` doesn't mean you can add anything to the collection. It means you can only get values from it. PECS means *Producer extends, Consumer super* – TheLostMind Dec 03 '15 at 07:33
  • Consider this statement: `List extends Base> list = new ArrayList()`. Perfectly valid assuming `Other implements Base`. However, the list cannot store `Base` objects or `Derived` objects, only `Other` objects, and by declaring `list` like you did, Java cannot ensure that the actually list is not a `List`, so without that ensurance, you cannot add *anything* to the list, you can only extract values from the list. That's what the dup-link describes, in more detail. – Andreas Dec 03 '15 at 07:38
  • @Andreas If you cannot add anything to the list, why there is still some thing in that list(which we can extract from)? I mean, we can't add something to the list, so the list is always empty, and why we can extract something from it? – Sayakiss Dec 03 '15 at 07:43
  • Comment not understood. **Did you read the answer that was linked?** Did you understand it? Let me summarize. A `List extends Xxx>` can be read, but not written. A `List super Xxx>` can be written, but not read. A `List` can be both read and written. – Andreas Dec 03 '15 at 07:50

0 Answers0