1

In java8 when I try to write this code

List<? extends String> list = new ArrayList<>();
list.add("a");

I get an error

Required type: capture of ? extends String - Provided: String

When I try this code

List<String> stings1 = new ArrayList<>();
List<String> stings2 = new ArrayList<>();
stings1.addAll(stings2);

It works fine, however, the signature of addAll method is boolean addAll(Collection<? extends E> c); and it shouldn't accept the same type it extends like the previous example.

I'm curious if ? extends T should accept T or not!!

Ammar Hussein
  • 5,534
  • 5
  • 18
  • 37
  • 7
    `? extends T` includes `T` itself. But that's not the root of the problem. You cannot add anything to the list, since `?` could be any subtype of `String`. So you can't add a `String`. You can only retrieve `String`s from the list, because any subtype of `String` is assignable to a `String` variable. See also [PECS](https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super). – MC Emperor Dec 16 '19 at 18:46
  • 1
    [Q: What is PECS (Producer Extends Consumer Super)?](https://stackoverflow.com/questions/2723397) – Andy Thomas Dec 16 '19 at 18:51
  • 2
    Also note that `? extends String` does not make sense, since the `String` class is declared `final` and thus cannot be extended. – MC Emperor Dec 16 '19 at 19:55
  • @MCEmperor Thanks now I understand it, also I just used string as example didn't intend to inherit it. – Ammar Hussein Dec 16 '19 at 20:34

0 Answers0