Generics Interview Questions and Answers
Beginner Questions
Q1: What are the main benefits of using Generics in Java?
Answer: * Type Safety: The compiler checks type compatibility at compile time. * Elimination of Casts: No manual casting is required when retrieving elements. * Code Reusability: Classes, interfaces, and methods can be written once to operate on different types of data.
Q2: What is Type Erasure?
Answer: Type Erasure is the process where the Java compiler removes generic type parameter information after checking type safety, replacing them with raw Object references or bounded types in the compiled bytecode.
Intermediate Questions
Q3: What is the difference between List<Object> and List<?>?
Answer: * List<Object> is a concrete list that can hold any Java object, but you cannot assign a List<String> to it because generics are invariant. * List<?> is a wildcard list of an unknown type. You can assign a List<String> or a List<Integer> to it, but you cannot add elements to it (except null) because the compiler does not know what type the list contains.
Q4: Explain the PECS rule.
Answer: PECS stands for Producer Extends, Consumer Super: * Producer Extends: If you only read elements from a collection (it acts as a producer of data), use ? extends T. * Consumer Super: If you only write elements into a collection (it acts as a consumer of data), use ? super T.
Advanced Questions
Q5: What are Bridge Methods in Generics?
Answer: A bridge method is a synthetic method generated by the Java compiler during type erasure to preserve polymorphism. If a class overrides a method from a generic parent, the compiler adds a bridge method matching the parent's erased signature (which uses Object) and delegates calls to the subclass's specific method signature.
Back to Stacks Home: JCF Index