Reputation: 607
Because generic type information is erased at runtime, it is illegal to use the instanceof operator on parameterized types other than unbounded wildcard types.
I extract this statement from effective java edition 2. And it says that preferred way to use instanceOf is :
// Legitimate use of raw type - instanceof operator
if (o instanceof Set) { // Raw type
Set<?> m = (Set<?>) o; // Wildcard type
...
}
Can some body please explain the concept ?(I understood the reified and erasure concepts)
Upvotes: 0
Views: 1602
Reputation: 262504
If you understood how erasure works, you know that instanceof
has no way to check for the erased type, so it can only be used with the raw type.
Along the same lines, after you have established that the object is some sort of Set, you cannot be sure what kind of type the Set has. So you can only (safely) use Set<?>
(which means that everything you pull out from the Set cannot be narrowed down to more than Object
, and you cannot put in anything at all).
Upvotes: 7