Java SE 8 Programmer II — Question 23
Given:
public class Test<T> {
private T t;
public T get () {
return t;
}
public void set (T t) {
this.t = t;
}
public static void main (String args [ ] ) {
Test<String> type = new Test<>();
Test type 1 = new Test (); //line n1
type.set("Java");
type1.set(100); //line n2
System.out.print(type.get() + " " + type1.get());
}
}
What is the result?
Answer options
- A. Java 100 >java.lang.Integer@<hashcode> B. line n1 with:
- C. A compilation error occurs. To rectify it, replace Test<Integer> type1 = new Test<>(); line n2 with:
- D. A compilation error occurs. To rectify it, replace type1.set (Integer(100));
Correct answer: C
Explanation
The correct answer is C because the code at line n1 creates a raw type instance of Test, which causes an issue when trying to set an Integer at line n2. To fix the error, type1 needs to be declared with a specific type, such as Test<Integer>. Options A and D do not address the compilation error properly, while option B does not provide a solution.