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.

4
  • Answer for similar question Commented May 12, 2011 at 6:39
  • Is the return type of getList missing List? Commented May 12, 2011 at 6:41
  • Yes. Sorry. My Bad in copying. Fixed. And thanks for the notice. Question still remains. Commented May 12, 2011 at 6: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 ? Commented May 12, 2011 at 6:46

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

I'm not yet convinced this works as expected. The getList().add(MyElement) will work, but how do you declare the array list? List<? super IMyInterface> list = new ArrayList<A>(); will give compilation error (A implements IMyInterface). Could you post a minimal sample?
Declare it as ArrayList<IMyInterface>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.