1

Why is it not possible to do that?

List<User> users;

void set(List<? extends User> users) {
    this.users = users;
}

The compiler fails with error: incompatible types: List<CAP#1> cannot be converted to List<User>

Note that it can be casted but is reported as unchecked. Again, why?

this.users = (List<User>) users;

A bit of context: My goal is for the setter to be practical to use. A caller may want to pass a List<SubUser> and I want to allow it. I don't want to use <? extends User> on the member because then I'll have to put the same wildcard on public methods that returns the list and it doesn't make sens because the list has always to be assumed heterogeneous. The only solution I found is the cast.

apflieger
  • 912
  • 10
  • 18
  • One universal way of solving this problem is to wrap it with `Collections.unmodifiableList`. The inevitable linked duplicate will explain why these aren't subclasses of each other. – Louis Wasserman Oct 02 '20 at 19:55

0 Answers0