Java
Instanceof
Generics
Programming
Object-Oriented

Java instanceof with generic types

Codemia Knowledge Hub ·

You cannot write instanceof List<String> in Java, because generic type arguments are erased and are not available at runtime. Check against the wildcard form List<?> instead, and if the element type matters, inspect the elements yourself.

Generics mostly help at compile time, while instanceof checks the runtime type of an object you already have. Type erasure is what separates the two.

What instanceof checks

instanceof answers a runtime question: is this object an instance of this class or interface?

java
1Object value = "hello";
2
3if (value instanceof String) {
4    System.out.println("It is a String");
5}

If value is null, the result is false. If the object implements an interface or extends a class being tested, the result is true.

Modern Java also allows pattern matching with instanceof, which combines the check and the cast:

java
1Object value = "hello";
2
3if (value instanceof String text) {
4    System.out.println(text.toUpperCase());
5}

What generics give you

Generics improve compile-time type safety:

java
1import java.util.ArrayList;
2import java.util.List;
3
4List<String> names = new ArrayList<>();
5names.add("Ada");
6names.add("Linus");
7
8String first = names.get(0);
9System.out.println(first);

Because the list is declared as List<String>, the compiler prevents you from adding unrelated types and removes the need for casts when reading.

Why instanceof List<String> does not compile

This fails:

java
1import java.util.ArrayList;
2import java.util.List;
3
4Object names = new ArrayList<String>();
5
6if (names instanceof List<String>) {
7    System.out.println("Never compiles");
8}

At runtime, Java generally knows that the object is some kind of List, but not whether it is a List<String> or a List<Integer>. After compilation, both are effectively just List for runtime type checking.

Checking List<?> instead

You can check against the raw type, or better, against a wildcard:

java
1import java.util.ArrayList;
2import java.util.List;
3
4Object value = new ArrayList<String>();
5
6if (value instanceof List<?> list) {
7    System.out.println("List size = " + list.size());
8}

This is legal because List<?> means "a list of some unknown type," which needs no runtime knowledge of the erased type argument. It does not tell you the object is a List<String>, so you cannot conclude the elements are String values.

Avoid using raw List everywhere just to get instanceof to compile, since that throws away compile-time safety. Prefer List<?> when you mean "a list of unknown element type."

Validating element types at runtime

If the real question is "is this a list whose elements are strings," you have to inspect the contents:

java
1import java.util.List;
2
3static boolean isListOfStrings(Object value) {
4    if (!(value instanceof List<?> list)) {
5        return false;
6    }
7
8    for (Object item : list) {
9        if (!(item instanceof String)) {
10            return false;
11        }
12    }
13    return true;
14}
15
16public static void main(String[] args) {
17    System.out.println(isListOfStrings(List.of("a", "b"))); // true
18    System.out.println(isListOfStrings(List.of("a", 1)));   // false
19}

This checks the elements, not generic metadata, which is the only honest runtime check available.

Wildcards in method signatures

Often a generic signature removes the need for a runtime check altogether:

java
1import java.util.List;
2
3static double sum(List<? extends Number> numbers) {
4    double total = 0;
5    for (Number n : numbers) {
6        total += n.doubleValue();
7    }
8    return total;
9}

This method accepts List<Integer>, List<Double>, and other numeric lists because it reads values as Number. More generally, a runtime type check is sometimes correct, but polymorphism, interfaces or generic method signatures are usually the better design.


Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Object-Oriented Design practice on Codemia

Turn requirements into classes, and defend the design, on the problems that come up in OOD rounds.

Practice OOD