Question 80 MSQ · 6.0 marks
Published solution
In `main()`, `findMax` is called with two different argument types: `Set<Integer> s` and `Set<Double> s1`.
**1. Why Generics or Upper-Bounded Wildcards are Needed:**
Both `Integer` and `Double` are subclasses of `Number`. In Java, generics are **invariant** (`Set<Integer>` is not a subtype of `Set<Number>`), so the method parameter must use either a generic type parameter `<T extends Number>` or an upper-bounded wildcard `Set<? extends Number>`:
- **Option B (`public static <T extends Number> void findMax(Set<T> s)`)**: Declares the generic type parameter `<T extends Number>` before the return type `void`. Calling `findMax(s)` infers `T = Integer`, and `findMax(s1)` infers `T = Double`. (**Valid**)
- **Option C (`public static void findMax(Set<? extends Number> s)`)**: Uses an upper-bounded wildcard `? extends Number`, which accepts a `Set` of any subtype of `Number` (`Set<Integer>` or `Set<Double>`). (**Valid**)
**2. Why Options A and D Fail:**
- **Option A**: Uses `Set<T>` without declaring `<T>` before the return type `void`, causing a compiler error (`cannot find symbol T`).
- **Option D**: Only accepts `Set<Double>`, so `findMax(s)` (where `s` is `Set<Integer>`) causes a compilation error.
**Answer: Options B and C.**
A: **Incorrect:** Fails to declare the type parameter `<T>` before the return type `void`, resulting in a compilation error.
B: **Correct:** Properly declares `<T extends Number>` as a generic method type parameter, accepting both `Set<Integer>` and `Set<Double>`.
C: **Correct:** Uses an upper-bounded wildcard `Set<? extends Number>`, which accepts `Set<Integer>` and `Set<Double>`.
D: **Incorrect:** `Set<Double>` cannot accept `Set<Integer> s` because generic types in Java are invariant.