0

I have a list with a syntax similar to this:

List<? extends MyInterface> list = new ArrayList<>();

I have an object that implements MyInterface, but using the above code, I am unable to add that object to the list:

Object object = getMyObject(); // I can only receive it here as Object
list.add((MyImplementation)object);

The following doesn't work either:

list.add((MyInterface)object);

Can anyone please point out what am I doing wrong here?

nullpointer
  • 430
  • 4
  • 17
  • 1
    I think you should read [What is PECS (Producer Extends Consumer Super)?](https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super) – takendarkk Feb 11 '19 at 21:14
  • tl;dr: the static type of `object` is `Object`. Thus, the compiler (rightfully) rejects `list.add(object)`. Please keep in mind that [types are erased after compilation](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html), thus Java has no chance to "see" that `object` is, in fact, `implements MyImplementation`. As @csmckelvey mentioned, you should apply PECS (Producer `extends` - Consumer `super`), i.e. use `super` instead of `extends` since your `list` consumes some `MyImplemntation`. – Turing85 Feb 11 '19 at 21:21

0 Answers0