Java collections covariance problem

You’re probably going to need to take a look at using wildcard types for generics. Here’s a quick link: What is PECS (Producer Extends Consumer Super)?

Quick answer: change the type to List<? extends AbstractItem>

Why can’t you just assign this?

Imagine the code here…

List<AbstractItem> foo = new ArrayList<SharpItem>();
foo.add(new BluntItem());

The static typing says this should work… but you can’t do that! It would violate the ArrayList’s type. That’s why this is disallowed. If you change it to

List<? extends AbstractItem> foo = new ArrayList<SharpItem>();

you can then do the assignment, but never add anything to the list. You can still retrieve elements from the list, however, as AbstractItems.

Is just using List (bare type) a good solution?

No, definitely not :-p

Leave a Comment