Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to cast from List<Optional> to List<Optional<?>>?

Tags:

java

generics

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.

like image 673
BeeOnRope Avatar asked Dec 05 '17 18:12

BeeOnRope


People also ask

Can I cast list to ArrayList?

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.

Why optional should not be used for fields?

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.

How do you cast optional to string?

In Java 8, we can use . map(Object::toString) to convert an Optional<String> to a String .


1 Answers

Yes, it's safe. The generic check is just at compile time.

like image 89
Lukas Bradley Avatar answered Sep 24 '22 02:09

Lukas Bradley