pinkpanther
pinkpanther

Reputation: 4798

Why there is no warning while casting from object to unbounded wildcard collection?

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?

Upvotes: 7

Views: 205

Answers (2)

newacct
newacct

Reputation: 122439

You get no "unchecked" warning because the cast is completely "checked" -- a cast to Map<?,?> only needs to ensure that the object is a Map (and nothing else), and that is completely checkable at runtime. In other words, Map<?,?> is a reifiable type.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691715

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.

Upvotes: 6

Related Questions