Entrance Exams
Govt. Exams
List list = new ArrayList();
list.add("Hello");
List raw = list; // Unchecked assignment
raw.add(123); // Adding Integer to raw type
String s = list.get(1);
Raw type assignment bypasses generics. Integer 123 is added to the list. When casting to String at get(1), ClassCastException occurs.
ArrayList<Integer> is a subtype of List<Integer> because ArrayList is a subclass of List with the same type parameter.
class Pair {
public void display(K key, V value) {
System.out.println(key + ": " + value);
}
}
Pair p = new Pair();
p.display("Age", 25);
The generic class Pair with two type parameters K and V correctly accepts String and Integer. The display method prints the key-value pair.
public T getMax(T a, T b) {
return a.compareTo(b) > 0 ? a : b;
}
What is the benefit of this recursive bound ?
Recursive bound <T extends Comparable<T>> ensures that T implements Comparable interface specifically for comparing with its own type, providing type safety.
List list = new ArrayList();
list.add(123); // Adding Integer
String s = (String) list.get(0);
Raw type List accepts any object. At runtime, the Integer 123 cannot be cast to String, causing ClassCastException.
PECS principle: use 'extends' when reading from a collection (source), use 'super' when writing to it (dest). Option A reads from source and writes to dest correctly.
List list = new ArrayList();
list.add(10);
Object obj = list.get(0);
System.out.println(obj instanceof Integer);
The Integer value is stored in the list. At runtime, type erasure converts it to Object, but the actual stored value remains an Integer instance.
interface Comparable { int compareTo(T o); }
Which class definition correctly implements this?
Option A correctly implements the generic interface by specifying the concrete type parameter as MyClass in the implements clause.
List<?> accepts any type but is read-only (can't add). List<Object> explicitly accepts Object type and allows adding objects.
Bounded type parameters restrict the types that can be used as arguments. T extends Number ensures T is Number or its subclass.