Why is there no warning when casting from an object to an unlimited collection of wildcards?

Why is there no warning for the code below?

public void some(Object a){ Map<?, ?> map = **(Map<?,?>)a**; //converting unknown object to map } 

I expected the RHS to have an unverified warning.

So far, this code has a warning:

 public void some(Object a){ Map<Object, Object> map = **(Map<Object,Object>)a**; //converting unknown object to Map<Object,Object> } 

In addition, there are no warnings for the following case:

 String str = (String) request.getAttribute("asd") //returns Object 

Does this mean that unverified warnings appeared with generics? Were there no such warnings before the introduction of generics in Java?

+7
java generics
source share
2 answers

You do not receive the โ€œuncheckedโ€ warning, because the throw is completely โ€œcheckedโ€ - casting to Map<?,?> Only requires the object to be Map (and nothing more), and this can be fully checked for at run time. In other words, Map<?,?> Is a reproducible type.

+1
source share

Yes, an uncontrolled warning applies only to generic types.

What this means: this dropping from Object to Map<T1, T2> may succeed because the object is really a Map, but due to erasing the runtime styles there is no way to verify that it is a Map<T1, T2> . Perhaps it will be Map<T3, T4> . Thus, you can very well violate the security of the map type by placing the elements T1, T2 inside you or get a ClassCastException when trying to read values โ€‹โ€‹from the map.

You have no warnings for the first cast, because you are using Map<?, ?> , Which means that the key and value type are unknown, which is true. You cannot perform an unsafe type operation on such a map without additional casts: you cannot add anything to such a map, and the only thing you can get are instances of Object .

+6
source share

All Articles