Govt Exams
java
List
With upper-bounded wildcard (? extends Number), you can read but cannot add elements (except null) because the compiler doesn't know the exact type.
java
List list = new ArrayList();
Will this compile?
Generics are invariant. ArrayList<Integer> cannot be assigned to List<Number> even though Integer is a subtype of Number. This prevents type safety issues.
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.