I have a question about generics in Java and instanceof operator.
It’s immposible to make such instanceof check:
if (arg instanceof List<Integer>) // immposible due to
// loosing parameter at runtime
but it’s possible to run this one:
if (arg instanceof List<?>)
Now comes my question – is there any difference between arg instanceof List and arg instanceof List<?> ?
Java Generics are implemented by erasure, that is, the additional type information (
<...>) will not be available at runtime, but erased by the compiler. It helps with static type checking, but not at runtime.Since
instanceofwill perform a check at runtime, not at compile time, you can not check forType<GenericParameter>in aninstanceof ...expression.As to your question (you probably seem to know already that the generic parameter is not available at runtime) there is no difference between
ListandList<?>. The latter is a wildcard which basically expresses the same thing as the type without parameters. It’s a way of telling the compiler “I know that I don’t know the exact type in here”.instanceof List<?>boils down toinstanceof List– which are exactly the same.