Practice Java generics interviews with wildcard read/write rules, a bounded copy API, erasure clashes and seven locally checked compiler/runtime cases.

Author: PracHub

Published: 11/21/2026

Java Generics Interview Questions: Wildcards, Type Erasure, and Heap Pollution

November 21, 2026

Quick Overview

Predict compiler errors, unchecked warnings and runtime failures with original Java examples. Connect wildcard bounds, capture and erasure to an API contract.

Software EngineerFree

An interviewer hands you two declarations: List<Integer> and List<Number>. You know that an integer is a number. The useful answer explains why assigning the first list to the second would let another caller insert a decimal into a list whose readers expect integers. Use that counterexample to explain wildcard choices, API design and the unchecked operations that can break the contract.

For Java generics interview questions, practice predicting a specific outcome before offering a definition: compilation succeeds, compilation fails, an unchecked warning appears, or a later operation throws. This guide uses the Java SE 25 language specification. Oracle's older wildcard tutorials are explicitly written for JDK 8; their relevant principles are checked against the specification here. The original examples were compiled locally with javac 25.0.5.1. They are practice cases, not reports of a particular employer's process.

Source and destination contracts for a generic copy operation

Begin with Design a generic key-value store and explain what the type parameter promises to callers. Then test that promise with a counterexample rather than adding a cast immediately.

Why is a list of integers not a list of numbers?

Official language rule: generic class types do not inherit the subtype relationship of their arguments. Although Integer extends Number, List<Integer> is not a subtype of List<Number>. Otherwise, code accepting the second type could call add(3.5), corrupting the first type's promise.

List<Integer> integers = new ArrayList<>();
List<Number> numbers = integers; // compilation error

Our local compiler rejected this assignment. A useful follow-up is why arrays behave differently: Java arrays are covariant and retain a runtime component type, which can produce ArrayStoreException. Ordinary generic collections enforce their parameter relationship primarily through compile-time checks. Do not use the behavior of Number[] as evidence that List<Number> accepts a list of integers.

If the method only needs to inspect numbers, change its parameter contract. A List<? extends Number> can refer to a list of integers or doubles while preserving an unknown specific element type. That unknown type is the reason the compiler restricts new writes.

What can you read and write through each wildcard?

Use the method's operations to choose the bound. The familiar producer-extends, consumer-super guideline describes what this method receives from or supplies to the collection.

Parameter viewReliable read typeRepresentative writeWhy
List<Integer>IntegerAn IntegerExact declared element type
List<? extends Number>NumberNo arbitrary non-null numberThe actual element type might be Integer or Double
List<? super Integer>ObjectAn IntegerThe actual element type can accept integers
List<?>ObjectNo arbitrary non-null objectThe element type is unknown

These are type-system permissions, not guarantees that an implementation supports mutation. List.of(...) remains unmodifiable even when the variable's generic type permits a write.

Also avoid calling an extends view strictly immutable. Adding null is type-correct; operations such as clear() can also be available. Our mutable-list example compiled and printed [1, 2, null] after a null insertion through an extends view. Whether null is accepted depends on the particular collection. The wildcard does not itself forbid it.

For a super view, the compiler cannot promise that an existing element is an integer: a List<Object> could already contain a string. Our separate example assigning x.get(0) directly to Integer failed compilation. Explain this asymmetry before reciting the mnemonic.

Design a copy method that preserves the relationship

Suppose a source produces integers and a destination accepts numbers. This original method appends each source element:

static <T> void copy(
        List<? super T> destination,
        List<? extends T> source) {
    for (T value : source) {
        destination.add(value);
    }
}

The same T connects the two parameters. The source supplies values compatible with T; the destination accepts them. A List<Integer> source and mutable List<Number> destination compiled and produced [1, 2] locally. This method appends; it does not implement the replacement and destination-size contract of every library method named copy.

Now explain why two independent wildcards are insufficient. With List<?> destination and List<?> source, the compiler has no relationship between their captured element types. The first could be a list of strings while the second contains integers. Naming a type parameter expresses the relationship that the operation actually needs.

Ask about aliasing too. This simple enhanced-for implementation does not promise safe self-copying while structurally modifying the same list. Null policy, mutation support, concurrent modification, and exception behavior are separate API decisions. Generics establish compatibility; they do not settle the whole behavioral contract.

When does wildcard capture help?

A helper method can give a name to one unknown type. Consider an operation that appends the first element of a nonempty, mutable list back to that same list:

static void duplicateFirst(List<?> values) {
    duplicateCaptured(values);
}

private static <T> void duplicateCaptured(List<T> values) {
    values.add(values.get(0));
}

The helper preserves one captured element type across the read and write. Our original wrapper and helper compiled; a list containing "a" became [a, a]. Empty lists and unmodifiable lists require their own behavior decisions; the example assumes neither.

Capture does not establish that two different lists have the same unknown element type. A helper cannot safely move a value from an arbitrary List<? extends Number> into another arbitrary one: one might hold integers and the other doubles. This is a good place to explain what information the signature lacks rather than suppressing the compiler's objection.

What does type erasure remove, and what remains?

Official specification: erasure maps a parameterized type to its raw generic type, and a type variable to the erasure of its leftmost bound. Thus an unbounded T erases to Object, while T extends Number erases to Number. Method signatures are subject to erasure too.

That explains why these declarations cannot coexist in one class:

void inspect(List<String> values) {}
void inspect(List<Integer> values) {} // same erasure

Our compiler rejected the name clash. Renaming one method or changing the API's actual parameter structure solves a different problem from casting the argument at a call site.

Avoid saying that every trace of generics disappears. Class files can retain generic signature metadata, and reflection can inspect declared generic types. This differs from recovering an arbitrary list instance's actual element type. List<String> and List<Integer> do not become separate runtime collection classes merely because their arguments differ.

The distinction also explains reifiability restrictions. An ordinary runtime instanceof List<String> check cannot verify every string element through that parameterized test. An unbounded List<?> test has a different status. Likewise, creating new T() is not supported simply because a method declares T; a factory or other explicit construction strategy is needed.

Bridge methods are another useful follow-up. Oracle documents compiler-generated bridges that preserve overriding behavior after erasure. If a stack trace points at a bridge or cast, trace the erased signature and actual argument instead of assuming the compiler has retained a separate implementation for every generic argument.

When reviewing an API change, distinguish source compatibility from binary behavior. Replacing a parameter with a differently bounded type can alter which calls compile, even when a superficial description still says “accepts a list.” Record the old signature, the proposed signature, and representative caller types before discussing migration. A warning-free caller under one declaration is not evidence that every existing caller remains valid under the other.

A related design question is whether the method should return a named type parameter or an unknown wildcard. If callers need to retain a relationship between the input and result, express that relationship directly. If they only inspect arbitrary values, an unknown type may be appropriate. Choose from the required operations and demonstrate a caller; avoid maximizing the number of wildcards as if that automatically made an API more flexible.

Trace heap pollution from the write to the failed read

Official term: heap pollution occurs when a variable of a parameterized type refers to an object inconsistent with that parameterized type. Raw-type operations and unsafe aliases involving arrays of non-reifiable element types are important routes into this state.

This deliberately unsafe original example illustrates the second route:

static void corrupt(List<String>... groups) {
    Object[] alias = groups;
    alias[0] = List.of(42);
    String value = groups[0].get(0);
}

Unsafe generic varargs traced from aliasing to a failed retrieval

We compiled this method and its invocation with -Xlint:unchecked. The compiler issued unchecked warnings. Execution then threw ClassCastException when retrieving the integer through the string-typed path. The aliasing write had already replaced the expected list; the later read exposed the violation.

Adding @SafeVarargs would assert a safety property this body does not have. It would not repair the write, restore the invariant, or make the runtime conversion valid. Explain why a method deserves the annotation before proposing it as warning cleanup.

For production review, prefer an API shape that avoids the unsafe array alias, or use a suitable collection-based input and preserve its type contract. If an unavoidable legacy boundary remains, validate and contain it. Keep any suppression narrow and document the invariant that makes that particular unchecked operation safe.

Rehearse the compiler-versus-runtime outcome

The following results come from independent local source files using the compiler version stated above. Failure in one file did not prevent checking another.

Original caseCompilationExecution or implication
Assign integer list to number listRejectedNo execution
Add integer through extends-number viewRejectedActual subtype is unknown
Read super-integer view directly as IntegerRejectedExisting values may only be known as Object
Overload using string-list and integer-list onlyRejectedErased signatures clash
Bounded copy into mutable number listAcceptedPrinted [1, 2]
Capture helper on mutable nonempty string listAcceptedPrinted [a, a]
Unsafe generic varargs aliasAccepted with unchecked warningsRetrieval threw ClassCastException

In an interview, give the predicted category, the type relationship responsible, and the smallest justified repair. Then describe which test would challenge your repair. This makes a generics answer useful in API reviews and debugging, where a definition alone cannot explain why the failing line is safe or unsafe.

These candidate-reported records provide adjacent practice rather than predictions of an exact employer interview. Their platforms and contexts may differ from this article. Question details and solutions can depend on account access.

PracHub questionWhat to rehearse
Design a generic key-value storeState the generic key/value relationship and counterexamples.
Explain Java follow-ups after solving coding problemExplain a compiler result before proposing a cast.
Implement iterators and write tests in JavaSeparate iterator behavior and collection type contracts.
Test-Driven Pair Programming: Grow a Java Set Class from Unit TestsGrow a Java collection API with behavioral checks.
Function Signature Lookup with Exact and Variadic Parameter MatchingDistinguish signature matching from Java erasure rules.

Start with Design a generic key-value store. Predict the type relationship and observable outcome before choosing a repair.

Sources and Further Reading

Research rechecked November 20, 2026. The recorded Java compiler and runtime checks were executed locally. They are original practice examples, not a report of an employer’s interview.


Comments (0)