Cannot Use instanceof with Parameterized Types
You'll learn why checking obj instanceof List<String> fails at compile time due to type erasure.
The Core Problem
In Java, you cannot use the instanceof operator with parameterized types. Code like this is illegal:
if (obj instanceof List<String>) { // Compile error!
// ...
}
The compiler rejects this because of type erasure—the mechanism that removes all generic type information at runtime.
Why Type Erasure Makes This Impossible
Remember that type parameters like <String> only exist at compile time. After compilation, List<String>, List<Integer>, and List<?> all become the same raw type: List.
At runtime, the JVM has no way to tell whether a List contains String, Integer, or any other type. The type parameter information is gone—erased. Since instanceof checks types at runtime, it cannot verify something that doesn't exist anymore.
What You Can Do Instead
You can only use instanceof with the raw type or unbounded wildcard:
if (obj instanceof List) { // OK: raw type check
List rawList = (List) obj;
// ...
}
if (obj instanceof List<?>) { // OK: unbounded wildcard
List<?> wildcardList = (List<?>) obj;
// ...
}
Both approaches confirm the object is some kind of List, but they cannot verify what type of elements it contains.
The Analogy
Think of it like checking if a box is a "toy box" versus checking if it's specifically a "toy box containing only red cars." At runtime, you can see it's a toy box, but you'd have to open it and inspect every toy to verify they're all red cars—and Java's type system doesn't provide that mechanism.
Key Takeaway:
You cannot use instanceof with parameterized types like List<String> because type erasure removes type parameters at runtime, making them unavailable for runtime type checks.