2

In java I have an arraylist that holds the following

 List<IMyInterface>

I am returning it in a function

List<? extends IMyInterface> getList()

Now I wanna do the following

getList().add(MyElement)

where MyElement extends the interface.

What I get is a compile error that the method was expecting something else.
here it is:

add (capture ) in list cannot be aplied to (MyElement).

. though MyElement extends th IMyInterface

BTW: What is the word Capture in bold ? Thanks.

Bick
  • 17,833
  • 52
  • 146
  • 251
  • [Answer for similar question](http://stackoverflow.com/questions/5974065/java-generic-question/5974147#5974147) – Prince John Wesley May 12 '11 at 06:39
  • Is the return type of getList missing List? – Jan Zyka May 12 '11 at 06:41
  • Yes. Sorry. My Bad in copying. Fixed. And thanks for the notice. Question still remains. – Bick May 12 '11 at 06:42
  • John . This link is really great. John skeet has in his comment just the answer to my question. It is just that I dont get it :0) . why is working like that not safe ? – Bick May 12 '11 at 06:46

1 Answers1

2

Add is a consumer method, it consumes things to be added to the list, so you want any list you add things to to be bounded below (? super Foo) rather than above (Foo extends ?).

See this question on PECS for more detail.

To make it more concrete, imagine the underlying was List<MyBetterInterface>, where MyBetterInterface extends IMyInterface. Now you'd still be OK to implement the getList() method with the same signature - but it is clearly not valid for a caller to add an object which implements only IMyInteface since now you'd have some objects which are not MyBetterInterface in there.

So declare it as

List<? super IMyInterface> getModifiableList();
Community
  • 1
  • 1
BeeOnRope
  • 60,350
  • 16
  • 207
  • 386