If you have a raw type in Java, you can safely assign/cast this to the same type with an unbounded wildcard. For example a List
can be safely cast to a List<?>
, which removes its raw nature and allows you to use it in a safe (type-checked) manner1.
On the other hand, Java doesn't let you cast from a List
itself parameterized with a raw type, like List<Optional>
to a list of the same type parameter with an unbounded wildcard, like List<Optional<?>>
.
You can still do it by dropping all the way down a raw List
and back up again (implicitly via the assignment):
List<Optional> rawOptionalList = null;
List<Optional<?>> wildcardOptionalList = (List)rawOptionalList;
Of course, this triggers warning about unchecked conversion (from List
to List<Optional<?>>
).
It seems to me though that this conversion is guaranteed safe: isn't List<Optional<?>>
just as safe as List<Optional>
in the same way that casting a raw Optional
to an Optional<?>
is safe?
1 ... but you'll never be able to add anything to this list, since nothing will match the capture of ?
for the add(?)
method. That's the price you pay for safety.