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.
Convert list To ArrayList In Java. ArrayList implements the List interface. If you want to convert a List to its implementation like ArrayList, then you can do so using the addAll method of the List interface.
You should almost never use it as a field of something or a method parameter. So the answer is specific to Optional: it isn't "a general purpose Maybe type"; as such, it is limited, and it may be limited in ways that limit its usefulness as a field type or a parameter type.
In Java 8, we can use . map(Object::toString) to convert an Optional<String> to a String .
Yes, it's safe. The generic check is just at compile time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With