Advanced Generics — Concept Check
Questions on Advanced Generics. Advanced generics covers wildcards, bounded type parameters, PECS, type erasure effects, and generic methods for writing flexible, reusable APIs.
Questions in this quiz
8 questions on Advanced Generics — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.You have a method `public static <T> T findMax(List<T> list)` using `T extends Comparable<T>`. What is the purpose of `T extends Comparable<T>`?
- ATo allow T to be compared with any other type.
- BTo restrict T to only primitive types.
- CTo ensure T can be compared to itself for ordering.
- DTo enable T to be used in mathematical operations.
2.A developer uses `List<? super Integer>` in a method signature. What can they do with the list?
- ARead any type of Number from the list.
- BRead Integer values from the list.
- CAdd any type of Number to the list.
- DAdd Integer or its subtypes to the list.
3.You need to copy elements from one list to another using `Collections.copy`. How should you declare the method parameters?
- A`List<? super T> src, List<? extends T> dest`
- B`List<T> dest, List<T> src`
- C`List<? extends T> dest, List<? super T> src`
- D`List<? super T> dest, List<? extends T> src`
4.A method uses `TypeReference<T>` to deserialize JSON. Why is this necessary?
- ATo avoid runtime exceptions during JSON parsing.
- BTo simplify the JSON parsing code.
- CTo retain generic type information during deserialization.
- DTo improve performance of JSON deserialization.
5.What happens if you try to instantiate a generic type `T` using `new T()` in Java?
- AWorks only if T has a no-arg constructor.
- BCompile-time error due to type erasure.
- CThrows a runtime exception.
- DCreates a new instance of the type T.
6.A developer mistakenly believes `List<String>` and `List<Integer>` are different classes at runtime. What is the truth?
- AThey differ only in memory allocation.
- BThey are the same class due to type erasure.
- CThey are different classes due to type safety.
- DThey are different because of JVM optimization.
7.Why can't you use `instanceof` with generic types like `List<String>`?
- AGeneric types are erased to their raw types at runtime.
- BIt is only allowed with primitive types.
- CIt leads to a syntax error in Java.
- DIt causes a runtime performance penalty.
8.When should you use `? extends T` in a method parameter?
- AWhen you need to convert types within the collection.
- BWhen you only need to read from the collection.
- CWhen you need to both read and write.
- DWhen you need to write to the collection.