Java Generics Interview Questions
Comprehensive java generics interview questions and answers for Java. Prepare for your next job interview with expert guidance.
Questions Overview
1. What are Generics in Java and what problem do they solve?
Basic2. Explain type erasure in Java Generics.
Basic3. What is the difference between <? extends T> and <? super T> wildcards?
Moderate4. How do you define and use generic methods in Java?
Basic5. What are bounded type parameters and when should they be used?
Moderate6. How does type erasure affect method overloading with generics?
Advanced7. What are reifiable and non-reifiable types in Java?
Advanced8. How do you implement a generic singleton pattern?
Advanced9. What is the GetAndPut Principle (PECS) in Java Generics?
Moderate10. How do you work with generic type inheritance?
Advanced11. What are the limitations of generic array creation and how to work around them?
Advanced12. How do you use type tokens to work around type erasure?
Advanced13. What is recursive type bound and when is it useful?
Advanced14. How do you implement generic variance in Java?
Advanced15. What are raw types and why should they be avoided?
Basic16. How do you implement generic type constraints?
Moderate17. What is heap pollution and how can it occur with generics?
Advanced18. How do generics interact with reflection?
Advanced19. What are type witnesses and when are they needed?
Moderate20. How do you design generic APIs effectively?
Moderate1. What are Generics in Java and what problem do they solve?
BasicGenerics enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods. They solve problems of: 1) Type safety by catching errors at compile time rather than runtime, 2) Elimination of type casting, 3) Enable implementation of generic algorithms. Introduced in Java 5 to provide compile-time type checking and remove risk of ClassCastException.
2. Explain type erasure in Java Generics.
BasicType erasure is the process where compiler removes all type parameters at runtime for backward compatibility. Effects: 1) Generic type information only available at compile time, 2) Raw types at runtime, 3) Type parameters replaced with bounds or Object, 4) Bridge methods generated for inheritance. Limitations: can't create generic arrays, no runtime type information, no static fields of type parameters.
3. What is the difference between <? extends T> and <? super T> wildcards?
ModerateUpper bounded wildcard <? extends T> allows reading from collection but not writing (producer). Lower bounded wildcard <? super T> allows writing to collection but limited reading (consumer). PECS principle: Producer-Extends, Consumer-Super. Upper bound useful for read-only operations, lower bound for write-only operations. Unbounded wildcard <?> when both type parameters are unknown.
4. How do you define and use generic methods in Java?
BasicGeneric methods declared with type parameter before return type: <T> T methodName(T arg). Can have different type parameters than containing class. Type inference often allows omitting explicit type arguments. Static generic methods possible unlike static fields. Multiple type parameters allowed. Bounded type parameters supported. Generic constructors also possible.
5. What are bounded type parameters and when should they be used?
ModerateBounded type parameters restrict what types can be used with a generic class/method. Single bound: <T extends UpperBound>, multiple bounds: <T extends Class & Interface1 & Interface2>. Uses: 1) Accessing methods of bound type, 2) Ensuring type compatibility, 3) Expressing relationships between types. Class must be first in multiple bounds. Improves API design and type safety.
6. How does type erasure affect method overloading with generics?
AdvancedType erasure can cause method signature conflicts: List<String> and List<Integer> become same signature after erasure. Bridge methods generated for covariant returns in inheritance. Cannot overload methods differing only in generic type parameters. Solutions: use different method names, add additional parameters, use type tokens. Important for API design and inheritance hierarchies.
7. What are reifiable and non-reifiable types in Java?
AdvancedReifiable types maintain runtime information: primitives, non-generic types, raw types, unbounded wildcards. Non-reifiable types lost during type erasure: generic types with parameters, bounded wildcards. Implications: can't create generic arrays, instanceof limitations, method overloading restrictions. Important for understanding generic type system limitations.
8. How do you implement a generic singleton pattern?
AdvancedGeneric singleton challenges: 1) Type parameter not available for static methods/fields, 2) Multiple type parameters create multiple instances. Solutions: 1) Generic static factory method, 2) Enum-based implementation, 3) Type token approach. Consider thread safety, serialization. Best practices: limit type parameters, document limitations, consider builder pattern alternative.
9. What is the GetAndPut Principle (PECS) in Java Generics?
ModeratePECS: Producer Extends, Consumer Super. Use <? extends T> when reading values (producing), <? super T> when writing values (consuming). Examples: copy(List<? extends T> src, List<? super T> dest). Improves API flexibility and type safety. Related to covariance and contravariance. Essential for collection framework design.
10. How do you work with generic type inheritance?
AdvancedGeneric type inheritance rules: 1) Box<Integer> not subtype of Box<Number> even if Integer extends Number, 2) Generic class inheritance uses type parameters in extends clause, 3) Raw types bypass generic type checking. Bridge methods handle inheritance with different type parameters. Consider bounded type parameters for hierarchies.
11. What are the limitations of generic array creation and how to work around them?
AdvancedCannot create arrays of generic types due to type erasure. Workarounds: 1) Create Object array and cast, 2) Use ArrayList instead, 3) Pass array creation to method parameter, 4) Use reflection (Array.newInstance). Each approach has trade-offs in type safety, performance, complexity. Consider collections as alternative to generic arrays.
12. How do you use type tokens to work around type erasure?
AdvancedType tokens pass Class<T> objects to maintain runtime type information. Uses: 1) Generic factory methods, 2) Type-safe heterogeneous containers, 3) Reflection with generics. Implementation using Class.cast(), instanceof checks. Super type tokens (Neal Gafter) for preserving generic type information. Consider performance implications.
13. What is recursive type bound and when is it useful?
AdvancedRecursive type bound: <T extends Comparable<T>>. Uses: 1) Implementing comparable types, 2) Builder pattern with fluent interface, 3) Self-referential generic types. Examples in natural ordering, comparable collections. Ensures type safety in comparison operations. Common in API design for fluent interfaces and type-safe comparisons.
14. How do you implement generic variance in Java?
AdvancedVariance handled through wildcards: covariance (? extends T), contravariance (? super T), invariance (T). Use cases: 1) Collection APIs, 2) Method parameters, 3) Return types. Related to Liskov Substitution Principle. Important for API design and collection framework usage. Consider PECS principle for proper usage.
15. What are raw types and why should they be avoided?
BasicRaw types are generic types without type parameters (List instead of List<String>). Problems: 1) Loss of type safety, 2) Potential runtime errors, 3) Mixing generic/non-generic code. Used for backward compatibility with pre-generics code. Modern Java should always use parameterized types. Exception: Class literals must use raw types.
16. How do you implement generic type constraints?
ModerateType constraints implemented through: 1) Bounded type parameters, 2) Multiple bounds, 3) Recursive type bounds, 4) Wildcards with bounds. Uses: ensuring method availability, type relationships, API contracts. Consider: readability, maintainability, type hierarchy complexity. Document constraints clearly. Balance flexibility and type safety.
17. What is heap pollution and how can it occur with generics?
AdvancedHeap pollution: variable of parameterized type refers to object not of that type. Causes: 1) Mixing raw and generic types, 2) Unchecked warnings, 3) Array covariance with generics. Prevention: 1) Address unchecked warnings, 2) Avoid raw types, 3) Use @SafeVarargs when appropriate. Can lead to runtime failures. Important for type safety.
18. How do generics interact with reflection?
AdvancedReflection with generics challenges: 1) Type erasure limits runtime information, 2) Getting/setting generic types, 3) Creating generic arrays. Solutions: Type tokens, ParameterizedType interface, GenericArrayType. Consider performance impact, maintainability. Useful for frameworks, dependency injection. Document reflection usage clearly.
19. What are type witnesses and when are they needed?
ModerateType witnesses explicitly specify type parameters when type inference fails. Required when: 1) Diamond operator ambiguity, 2) Generic method calls, 3) Anonymous inner classes. Syntax: ClassName.<Type>methodName(args) or new ClassName<Type>(). Improves code clarity, prevents inference errors. Consider readability vs verbosity trade-off.
20. How do you design generic APIs effectively?
ModerateGeneric API design principles: 1) Make declarations as general as possible, 2) Use bounded wildcards for flexibility, 3) Consider type parameter naming conventions, 4) Document type parameters, 5) Provide raw type compatibility, 6) Consider builder pattern for multiple type parameters. Balance usability, type safety, and maintainability. Address backward compatibility.