Course contents

Generics: interview questions & scenarios

Premium12 questions · 14 what-if follow-ups

These are the generics questions I ask when I want to know whether you can reason from type safety, not memorize angle-bracket syntax. Answer it out loud first, then open the model answer, and use the deeper lessons when you want the full path: Generics basics, How type erasure works, Wildcards and PECS and Bounded types and generic methods.

Question 1. ConceptWarm-upAsked very often

Why did Java add generics, and why are raw types dangerous?

Tests compile-time type safety, raw types, unchecked warnings

Show answerHide answer1 follow-up

Model answer

Generics let you express type relationships that javac can check. List<String> says this list is meant to contain strings, so list.add(42) is rejected where the bug is written instead of failing later when somebody reads the value as a String.

Raw types are the old pre-Java 5 form: List instead of List<String>. Java keeps them for migration compatibility, but a raw type turns off generic checking for that use and produces unchecked warnings. The warning matters because heap pollution can sit quietly inside a collection until a compiler-inserted cast fails on a later read.

import java.util.ArrayList;
import java.util.List;

public class Main {
    static void addWrong(List raw) {
        raw.add(404);                    // unchecked warning with -Xlint:unchecked
    }

    public static void main(String[] args) {
        List<String> statuses = new ArrayList<>();
        statuses.add("PAID");
        addWrong(statuses);

        for (String status : statuses) { // ClassCastException on 404
            System.out.println(status.toLowerCase());
        }
    }
}

Prefer List<?> when the element type is unknown but you still want type checking. Use raw types only at old API boundaries, and keep any @SuppressWarnings("unchecked") as narrow as possible.

How I’d say it in the interview

"Generics move type mistakes from runtime to compile time. Before generics, a list was basically List of Object, so every read needed a cast and a bad write could fail much later. A raw type brings that risk back, so I treat unchecked warnings as bugs unless I can prove the boundary is safe."

Signals depth

Calling out List<?> as the safe "unknown list" shape. Many candidates say raw types are for mixed lists, but mixed still has a type, often List<Object> or a domain wrapper.

Red flags

"Raw types are more flexible" or "unchecked warnings are fine because the code compiles." The whole point is that the compiler stopped protecting you.

Follow-ups interviewers ask next

  1. What if I really need to call an old raw API?

    Wrap the boundary. Convert or validate the values once, store them in a typed collection, and put the unchecked suppression on the smallest local assignment with a comment explaining why it is safe.

Question 2. What does it print?CoreAsked very often

Why is List<Integer> not a List<Number>, while String[] can be an Object[]? What does this print?

Tests invariance, array covariance, ArrayStoreException

Show answerHide answer1 follow-up

Model answer

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> ints = new ArrayList<>(List.of(1, 2));
        // List<Number> numbers = ints;       // compile-time error
        List<? extends Number> readable = ints;
        System.out.println(readable.get(0));

        String[] strings = {"paid"};
        Object[] objects = strings;
        try {
            objects[0] = 42;
        } catch (ArrayStoreException ex) {
            System.out.println(ex.getClass().getSimpleName());
        }
    }
}

It prints:

1
ArrayStoreException

Generic types are invariant. If Java allowed List<Integer> to be assigned to List<Number>, the List<Number> reference could add a Double, corrupting a list that promised integers. Java rejects that at compile time.

Arrays are covariant for older language reasons. A String[] can be viewed as an Object[], but the array keeps its runtime component type. When you store an Integer, the runtime checks the component type and throws ArrayStoreException.

How I’d say it in the interview

"Generics prevent the bad write before the program runs. Arrays allow the assignment, then check every store at runtime. So List<Integer> is not a List<Number>, but String[] is an Object[] until you try to put a non-string in it."

Signals depth

Saying that List<? extends Number> is the safe read-only view for a List<Integer> when you only need to read numbers.

Red flags

"Because generics use objects and arrays use primitives" or "List<Integer> should be a List<Number> because inheritance says so." The issue is writes through the wider reference.

Follow-ups interviewers ask next

  1. What if I only need to sum the values?

    Use List<? extends Number> in the parameter. The method can read every element as a Number, and it does not need to add anything.

Question 3. ConceptCoreAsked very often

What is type erasure, and what generic information survives at runtime?

Tests erasure, casts, Signature attribute, reifiable types

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 4. ConceptSeniorCommonly asked

What is a bridge method, and why does the compiler generate one for generics?

Tests erasure, overriding, Comparable, synthetic methods

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 5. CodingCoreAsked very often

Why can't you write new T() or new T[], and what are the usual workarounds?

Tests erased type parameters, Class tokens, Supplier, array factories

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 6. DebuggingCoreCommonly asked

This overload fails with name clash: have the same erasure. Debug it.

Tests erased signatures, overload resolution, API design

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 7. DesignSeniorCommonly asked

How would you get the class of a generic type, and when would you use a super type token like Jackson's TypeReference?

Tests Class<T>, ParameterizedType, super type token, Jackson TypeReference

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 8. ScenarioCoreAsked very often

Explain PECS using Collections.copy.

Tests producer extends, consumer super, Collections.copy

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 9. DebuggingCoreAsked very often

This code says List<? extends Number>, so why does add(10) fail?

Tests wildcard capture, extends read safety, CAP variables

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 10. ConceptSeniorCommonly asked

Walk me through <T extends Comparable<? super T>>. Why not just <T extends Comparable<T>>?

Tests recursive bounds, lower-bounded comparable, max signatures

Model answer, how to say it, 2 follow-ups: unlock with the Java Pass

Question 11. DesignSeniorCommonly asked

When would you choose a wildcard instead of a type parameter?

Tests API design, wildcard capture, Effective Java rule

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 12. DebuggingSeniorCommonly asked

What is heap pollution, and when is @SafeVarargs actually safe?

Tests heap pollution, generic varargs, @SafeVarargs, unchecked warnings

Model answer, how to say it, 2 follow-ups: unlock with the Java Pass

Premium question set

Keep reading with the Java Pass

The rest of this question set is part of Java One-Stop Interview Prep: in-depth explanations, diagrams, model answers and how to say them in the interview.

From ₹199 · one-time payment · No auto-renewal

Lessons in Generics