Which of these declarations would NOT cause a compilation warning or error?
AList list = new ArrayList();
BList list = new ArrayList();
CList list = new ArrayList();
DList list = new ArrayList();
Correct Answer:
A. List list = new ArrayList();
EXPLANATION
Option A uses proper diamond syntax with matching type parameters on both sides. Options B, C produce unchecked warnings, and Option D is invalid due to invariance.
What will be the result of this code?
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);
AClassCastException when accessing list.get(1)
BCode executes without error
CCompilation error
DStringIndexOutOfBoundsException
Correct Answer:
A. ClassCastException when accessing list.get(1)
EXPLANATION
Raw type assignment bypasses generics. Integer 123 is added to the list. When casting to String at get(1), ClassCastException occurs.
What is the output of this generic code?
class Pair {
public void display(K key, V value) {
System.out.println(key + ": " + value);
}
}
Pair p = new Pair();
p.display("Age", 25);
AAge: 25
BCompilation error - type mismatch
CAge: 25.0
DRuntime exception
Correct Answer:
A. Age: 25
EXPLANATION
The generic class Pair with two type parameters K and V correctly accepts String and Integer. The display method prints the key-value pair.
Consider this code:
public T getMax(T a, T b) {
return a.compareTo(b) > 0 ? a : b;
}
What is the benefit of this recursive bound ?
AEnsures type safety by guaranteeing T implements Comparable with itself
BAllows T to be compared with any type
CImproves runtime performance
DEliminates the need for type erasure
Correct Answer:
A. Ensures type safety by guaranteeing T implements Comparable with itself
EXPLANATION
Recursive bound <T extends Comparable<T>> ensures that T implements Comparable interface specifically for comparing with its own type, providing type safety.
Which of these correctly demonstrates the Producer Extends Consumer Super (PECS) principle?
Apublic void process(List
Bpublic void process(List
Cpublic void process(List source, List dest) { }
Dpublic void process(List source, List dest) { }
Correct Answer:
A. public void process(List
EXPLANATION
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.