简体   繁体   中英

Why does the List<? extends Foo> not accept an object of the Foo class?

I tried to add an object of the class Foo to a List<? extends Foo> List<? extends Foo> , but the code does not compile.

final Foo[] array = new Foo[] {new Foo()};
final List<? extends Foo> list = new ArrayList<>(array.length);
for (final Foo foo : array)
{
     // The List<? extends Foo> does not accept the foo object.
     list.add(foo);
}

Here is the question again: why is that the case? That doesn't make any sense, does it? I just want a List that can contain objects who extend the Foo class.

I think you're misunderstanding what List<? extends Event> List<? extends Event> actually means . It doesn't mean "I can add any subclass of Event to this list". That's simply what a List<Event> is, since subclasses can be upcast to Event . List<? extends Event> List<? extends Event> says "there is some subclass of Event which restricts this type". So if foo has type List<? extends Event> List<? extends Event> , then foo could feasibly be a List<Event> , but it could also be a List<SomeSpecificTypeOfEvent> , in which case you aren't allowed to add things that aren't SomeSpecificTypeOfEvent to it. I think what you want is simply List<Event> ; the wildcard is overkill here and is not necessary.

Further reading on variance annotations ( extends and super ): https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)

Edit : As Johannes Kuhn pointed out in the comments, if all you're doing is adding elements to the list, then the most general type you can have is not List<Event> but List<? super Event> List<? super Event> , since you could feasibly pass a list of any supertype of Event and your method would still work correctly. Some care must be taken, as using ? super Event ? super Event could cause some issues trying to access list elements later, but if all you're doing in the method is writing to the list, then it works perfectly.

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