Govt. Exams
Entrance Exams
public T findMax(T a, T b)
Multiple bounds in generics use '&' to specify that the type must satisfy all constraints. T must extend Number AND implement Comparable<T>.
Generics are invariant in Java. List<Integer> is NOT a subtype of List<Number> to maintain type safety. This is a key feature preventing runtime errors.
List strings = (List) getSomeList();
Due to type erasure, casts involving generic types are unchecked. The compiler warns about this but allows it. The actual cast check only verifies the raw type.
Which assignment is valid?
Nested generics must match exactly or use appropriate wildcards. Only option D provides exact type match. Option B would work with wildcards, but that's not listed correctly here.
Option D correctly ensures T is comparable with itself using F-bounded polymorphism. Option C has inverted logic with '? super'. Option B is unnecessarily complex.
public class Pair { }
Which declaration is invalid?
Option D is invalid because we cannot instantiate a generic class with wildcard type parameters. Wildcards are only for variable declarations, not for instantiation with 'new'.
List strings = new ArrayList();
List raw = strings;
raw.add(123);
String str = strings.get(0);
The code compiles (with warnings about raw types) but throws ClassCastException at runtime when trying to cast Integer to String. Type safety is lost with raw types.
We can read from map.get() and assign to List<?>, but cannot add to List<?> or put into the map due to wildcard restrictions. Option C only reads the value.
public static T findMax(T[] array)
The bounded type parameter 'T extends Comparable<T>' enforces that T must implement Comparable and be comparable with its own type. This is the F-bounded polymorphism pattern.
Java does not allow covariance with generics. List<Integer> cannot be assigned to List<Number> because you could add a Double to the latter, breaking type safety.