0

In the simple case, I can easily downgrade from a generic type to a wildcard type:

List<Integer> intList = new ArrayList<>();
List<?> wildList = intList; // I can cast to a List<?>

However, as my generics get more complicated:

List<List<Integer>> nestedIntList = new ArrayList<>();
List<List<?>> nestedWildList = nestIntList; // This does not compile

Is there a way that this can be made to compile? Am I missing some logical case that the compiler is protecting me from? Why can I not cast the inner type?

John Petry
  • 16
  • 1

1 Answers1

1

List<Integer> is assignable to List<?> or List<? extends Integer>. Similarly you can assign it to a List<? extends Number> but not to List<Number>.

On similar lines, you can only assign List<List<Integer>> to List<? extends List<?>>

See:

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

Java generics, nested collection of wildcard

Thiyagu
  • 17,362
  • 5
  • 42
  • 79