0

I have a list defined like this:

 List<MyBean> beanList = getList();

getList() returns type List<MyBean>.

Now, I want to pass the result to a method that receives List<Idisplayable> and MyBean does implements Idisplayable

This causes a compiler error.

Now it would be stupid to iterate over beanList just to cast it into Idisplayable. suggestions?

0

3 Answers 3

11

if the method that takes a List<IDisplayable> doesn't want to add anything to the list, then it should accept a List<? extends IDisplayable> instead, exactly to allow what you're trying to do.

The basic problem is that a List<MyBean> is not the same thing (or even assignment-compatible with) a List<IDisplayable>.

A List<IDisplayable> promises two things: It will only ever return IDisplayable objects and it will accept (via add()) all IDisplayable objects.

A List<MyBean> also only ever returns IDisplayable, but it will not accept any IDisplayable that is not also a MyBean (say, a AnotherDisplayable, for example).

So if a method only iterates over the content of a list (effectively being read-only) or only does a limited set of manipulation (removing objects is fine, as is adding null), then it should accept List<? extends IDisplayable> instead. That syntax means "I accept any List that will only ever return IDisplayable objects, but I don't care about the specific type".

Sign up to request clarification or add additional context in comments.

2 Comments

Nice, I didn't know about being able to add null. Good point
@Lukas: it's a little fact that I took quite a while to learn.
6

Make your method accept <? extends Idisplayable>

public void myMethod(List<? extends Idisplayable> list);

Comments

1

You have 2 options:

If you have access to the method and it does not change the list, only in this case you may update the signature:

public void myMethod(List<? extends Idisplayable> list);

As an alternative option you may try:

List<Idisplayable> list = new ArrayList<Idisplayable>();
list.addAll(getList());

and then pass list to your method that takes List<Idisplayable> list

The point is that Collection.addAll is declared as:

addAll(Collection<? extends E> c), as a result, you may pass here both List<Idisplayable> and List<MyBean>

Comments

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.