Java Generics Interview Questions
Last updated 2026-11-19
Generics look simple until an interviewer asks why you cannot write new T[] or why List<Object> is not a supertype of List<String>. The questions below cover the design reasons, the erasure model that causes most surprises, and the wildcard rules (extends, super and PECS) that people routinely confuse.
All code compiles on Java 17 unless a comment says it is an error. For collection-specific usage see Java collections questions.
| Introduced | Java 5, implemented by type erasure |
|---|---|
| Key rule | PECS: producer extends, consumer super |
| Java version | 17 and later |
The mental model
Generics are a compile-time feature. The compiler checks types, inserts casts and then erases the type arguments, so at runtime a List<String> and a List<Integer> are the same class, List. Almost every limitation you will be asked about follows from that single fact.
Java Generics Interview Questions: questions with worked answers
1 Why were generics added, and what is the benefit over raw collections?
easyBefore Java 5 collections held Object, so you cast on every read and a wrong type failed at runtime with ClassCastException. Generics move that check to compile time and remove the casts. They also let you write one algorithm, such as a max or a cache, that works for many types while remaining type safe.
2 What is type erasure and what does it prevent?
mediumThe compiler replaces each type parameter with its bound (or Object), inserts casts where needed and emits no type argument information in the bytecode. Consequences: you cannot write new T(), new T[], T.class or an instanceof check against List<String>, you cannot overload methods that differ only in type arguments, and a static field cannot use the class type parameter.
javaList<String> a = new ArrayList<>(); List<Integer> b = new ArrayList<>(); System.out.println(a.getClass() == b.getClass()); // true // if (a instanceof List<String>) {} // compile error // void m(List<String> x) {} void m(List<Integer> x) {} // same erasure: error3 Why is List<Object> not a supertype of List<String>?
mediumIf it were, you could pass a List<String> as a List<Object> and add an Integer to it, breaking type safety. Generics are invariant: List<String> is not a List<Object> even though String is an Object. Arrays are covariant instead and defer the check to runtime with ArrayStoreException.
javaObject[] arr = new String[1]; // arr[0] = 1; // compiles, throws ArrayStoreException at runtime List<String> ls = new ArrayList<>(); // List<Object> lo = ls; // compile error4 Explain wildcards and the PECS rule.
medium? extends T accepts any subtype, so the structure is a producer you can read T from but not add to (except null). ? super T accepts any supertype, so it is a consumer you can add T to, while reads yield only Object. Remember Producer Extends, Consumer Super. Unbounded ? means unknown type and is for code that only uses Object methods.
javastatic <T> void copy(List<? super T> dest, List<? extends T> src) { for (T t : src) dest.add(t); // read from src, write to dest } List<Number> nums = new ArrayList<>(); copy(nums, List.of(1, 2, 3)); // Integers into a List<Number> System.out.println(nums); // [1, 2, 3]5 What is the difference between List<?> and List<Object>?
mediumList<Object> is a list you can add any object to, but you can only pass a List<Object> to it. List<?> is a list of some unknown type that accepts any List<X> as an argument, but you cannot add anything to it except null. Use List<?> for read-only generic utilities such as printing sizes.
6 Write a generic method that returns the maximum of a list.
mediumBound the type parameter with Comparable so that compareTo exists. For maximum flexibility use <T extends Comparable<? super T>>, which also accepts a class whose compareTo is inherited from a superclass. Return an Optional or throw on an empty list.
javastatic <T extends Comparable<? super T>> T max(List<? extends T> list) { T best = list.get(0); for (T t : list) if (t.compareTo(best) > 0) best = t; return best; } System.out.println(max(List.of(3, 9, 4))); // 97 What is a raw type and why is it dangerous? Predict the output.
mediumA raw type is a generic class used without type arguments. The compiler skips generic checks and only warns, so you can put the wrong type into a collection (heap pollution) and the failure surfaces later, at a cast the compiler inserted elsewhere.
javaList<String> strings = new ArrayList<>(); List raw = strings; raw.add(42); // unchecked warning only try { String s = strings.get(0); // ClassCastException here } catch (ClassCastException e) { System.out.println("CCE"); }8 Why can you not create a generic array, and what are the workarounds?
hardArrays carry their component type at runtime and check stores, but erasure makes T unavailable at runtime, so new T[n] and new List<String>[n] are rejected to prevent heap pollution going undetected. Workarounds: use a List<T> instead, create an Object[] and cast it inside a class that does not expose it (as ArrayList does), or pass a Class<T> token or an IntFunction<T[]> (as Stream.toArray does).
java@SuppressWarnings("unchecked") T[] arr = (T[]) new Object[10]; // inside a generic class, never returned directly String[] out = Stream.of("a","b").toArray(String[]::new);9 What are bridge methods?
hardWhen a class overrides a generic method with a concrete type, erasure would make the signatures differ. The compiler therefore generates a synthetic bridge method with the erased signature that casts and calls your method, preserving polymorphism. They show up in reflection and stack traces, and are why a class implementing Comparable<Emp> has a hidden compareTo(Object).
javaclass Emp implements Comparable<Emp> { public int compareTo(Emp o) { return 0; } // compiler adds: public int compareTo(Object o) { return compareTo((Emp) o); } }10 Can a static method or field use the class type parameter?
mediumNo. A type parameter belongs to an instance, and there is only one static member shared by all parameterisations, so Box<String> and Box<Integer> would share a field of impossible type. A static generic method can declare its own type parameter, as in static <T> Box<T> of(T v).
11 What is a recursive bound? Explain Enum<E extends Enum<E>>.
hardA recursive bound refers to the type parameter itself, such as <T extends Comparable<T>>, which says that T can be compared with other T. Enum<E extends Enum<E>> lets Enum define methods like compareTo(E) so each enum compares only with its own type, and is also used for fluent builders that return their own subtype from chained methods.
12 What is the diamond operator and how does inference work?
mediumDiamond (<>) asks the compiler to infer the type arguments of a constructor call from the target type, so Map<String, List<Integer>> m = new HashMap<>() needs no repetition. Java 9 allows it on anonymous classes. The var keyword (Java 10) infers the type of a local variable from its initialiser, so var list = new ArrayList<>() infers ArrayList<Object>, which is rarely what you want.
13 Which generic types are reifiable, and how do you get a type argument at runtime?
mediumReifiable types retain full type information at runtime: primitives, non-generic classes, raw types and unbounded wildcard types like List<?>. List<String> is not. You can read type arguments from class declarations through reflection, as in a subclass of a TypeReference<T> (the technique used by Jackson and Gson), because the superclass type with its arguments is stored in the class file.
14 What does @SafeVarargs do?
mediumGeneric varargs create a generic array, which causes an unchecked warning at every call. @SafeVarargs asserts that the method does not store anything in the array or expose it, and suppresses the warnings. It is allowed on static, final and private methods and constructors, and the standard Arrays.asList and List.of use it.
Frequently asked questions
What is the most common generics question?
Type erasure and wildcards. Expect "what is PECS" and "why can I not create a generic array" in most Java technical rounds.
Are generics available at runtime?
Only in limited places: class and method signatures retained by reflection. Type arguments of an instance are erased.
Is generics knowledge needed for freshers?
Basic usage of List<String> and Map<K,V> is expected. Wildcards and erasure are typical for 2 or more years of experience.
How do generics relate to collections?
Every java.util collection is generic. See Java interview questions for the basics.
Related guides
More in Programming Language Interview Questions by Language
- Java HashMap Internals Interview Questions
- Java Interfaces and Abstract Classes Interview Questions
- Java Interview Questions and Answers
- Java Multithreading Interview Questions
- Java OOPs Interview Questions
- Java String Interview Questions
- JavaScript Array Methods Interview Questions
- JavaScript Closures Interview Questions
- JavaScript Coding Interview Questions with Solutions
- JavaScript DOM Interview Questions
- JavaScript ES6 Interview Questions
- JavaScript Event Loop Interview Questions