Govt Exams
Generic methods require type parameter declaration before return type. The collection parameter must be of type Collection<T> to extract element of type T.
java
List list = new ArrayList();
list.add("Java");
Object obj = list;
System.out.println(list.getClass() == obj.getClass());
Generic type information is erased at runtime. Both list and obj refer to the same ArrayList class, so getClass() returns the same class object.
Option A demonstrates recursive type bound (also called F-bounded polymorphism), which allows a type to reference itself in its bound. This is commonly used in builder patterns and comparators.
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.
Java does not allow creation of arrays with parameterized types due to type erasure. List<String>[] would be unsafe. You must use List<String>[] or List[] instead.
Only option B allows adding elements safely. '? super Integer' means the collection can hold Integer or any supertype. Option A prevents adding, Option C prevents adding, Option D restricts to exactly Number.
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 void sort(T[] array)
With multiple bounds using '&', type erasure replaces T with the first bound. Here, Number is the first bound, so T is replaced with Number.