Why is there no warning for the below code?
public void some(Object a){
Map<?, ?> map = **(Map<?,?>)a**; //converting unknown object to map
}
I expected the RHS to have an unchecked warning.
While 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>
}
Also, for below case there is no warning:
String str = (String) request.getAttribute("asd") //returns Object
Does this mean that unchecked warnings came with generics? There were no such warnings before introduction of generics in Java?
2. What Does the “unchecked cast” Warning Mean? The “unchecked cast” is a compile-time warning. Simply put, we'll see this warning when casting a raw type to a parameterized type without type checking. An example can explain it straightforwardly.
An unbounded wildcard is the one which enables the usage of all the subtypes of an unknown type i.e. any type (Object) is accepted as typed-parameter. For example, if want to accept an ArrayList of object type as a parameter, you just need to declare an unbounded wildcard.
Yes, the unchecked warning is only relevant to generic types.
What it means is: this cast from Object to Map<T1, T2>
might succeed because the object is indeed a Map, but the runtime has no way, due to type erasure, to check that it's a Map<T1, T2>
. It might very well be a Map<T3, T4>
. So you might very well break the type-safety of the map by putting T1, T2 elements inside, or get a ClassCastException when trying to read values from the map.
You have no warning for the first cast because you're casting to a Map<?, ?>
, which means that the key and the value type is unknown, which is true. You won't be able to perform a type-unsafe operation on such a map without additional casts: you can't add anything to such a map, and the only thing you can get out of it is instances of Object
.
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