Interview Questions
Generics · Study material
Java Generics – Interview Questions
1. What are generics?
A way to parameterise classes, interfaces and methods by type for compile-time type safety and reuse.
2. What are the benefits?
Compile-time type checking, no casts, and reusable algorithms and data structures.
3. What is a generic method?
A method that declares its own type parameters before its return type, e.g. static <T> T first(List<T> l).
4. What is a bounded type parameter?
A type parameter restricted with extends, such as <T extends Number>, allowing calls to the bound's methods.
5. What is a wildcard?
The ? symbol representing an unknown type, optionally bounded: ? extends T or ? super T.
6. Explain PECS.
Producer Extends, Consumer Super: read from ? extends T, write to ? super T.
7. Why is List<Integer> not a List<Number>?
Generics are invariant; otherwise a Double could be added to a list of Integers.
8. What is type erasure?
The compiler removes generic type information after checking, replacing type parameters with their bounds and inserting casts.
9. Why can't you create new T()?
T is erased, so the run-time type is unknown; pass a Supplier<T> or Class<T> instead.
10. Why can't generics use primitives?
Type parameters erase to Object (or a bound), which primitives are not.
11. What is a raw type?
A generic type used without type arguments, e.g. List; it disables generic checks and exists for backward compatibility.
12. What is heap pollution?
A variable of a parameterised type referring to an object of a different parameterisation, usually through raw types or unchecked casts.
13. Can you overload methods that differ only in generic parameters?
No – f(List<String>) and f(List<Integer>) have the same erasure.
14. Can a generic class have static fields of type T?
No – static members are shared by all parameterisations.
15. What does <T extends Comparable<T>> mean?
T must be comparable to other T objects – a recursive bound.
16. Can you create a generic array?
Not directly (new T[n] or new List<String>[n]); use lists or an array of Object with a cast.
17. Can exception classes be generic?
No; catch clauses need the run-time type.
18. What is the diamond operator?
<> in new ArrayList<>(), letting the compiler infer type arguments (Java 7+).
19. What is @SafeVarargs?
An annotation promising that a generic varargs method does not misuse its array, suppressing heap-pollution warnings.
20. What is a bridge method?
A compiler-generated method that preserves overriding after erasure.