简体   繁体   中英

java generics and inheritance question

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?

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> 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> 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".

Make your method accept <? extends Idisplayable> <? extends Idisplayable>

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM