Reputation: 20080
I was expecting the following code to produce a rawtype warning, and it doesn't:
public class Test {
public void exampleMethod(Object object){
if(object instanceof Collection){
Collection<?> coll = (Collection) object;
System.out.println(coll);
}
}
}
Why a raw-type cast do not generate a warning?
Upvotes: 1
Views: 134
Reputation: 262494
The point of the warning is to inform you that the generic type assertion is not actually enforced by either compiler or runtime, so that you might get ClassCastExceptions further down in your code.
Because of the ?
on the left-hand side, you are not using the erased type, so that the cast does not have to pretend to check against that erased type. There is no situation where this line would result in a run-time error later on because of the unchecked type information. So no need to warn.
With Collection<?>
, when you get things out, you get an Object
. That won't fail (as everything you could possibly get is an Object
).
And you are not allowed to put anything into a Collection<?>
. So that won't cause errors either.
Upvotes: 3