What is the difference between List and List in practical usage?
AThey are identical
BList can accept any type; List cannot accept anything
CList can add Objects; List can only add null
DList is deprecated in favor of List
Correct Answer:
C. List can add Objects; List can only add null
EXPLANATION
List<Object> accepts Object and its subclasses for adding. List<?> (unbounded wildcard) is more flexible for reading but restrictive for writing (only null).
What will happen when you compile and run this code?
java
List strings = Arrays.asList("a", "b", "c");
List raw = strings;
raw.add(123);
String s = strings.get(3);
ACompiles successfully and runs without error
BCompilation error due to raw type usage
CCompiles with warning, throws ClassCastException at runtime
DCompiles and throws ArrayIndexOutOfBoundsException
Correct Answer:
C. Compiles with warning, throws ClassCastException at runtime
EXPLANATION
Assigning generic type to raw type suppresses type checking. The Integer added bypasses the type system, causing ClassCastException when retrieved as String.
Consider the code:
java
List list = new ArrayList();
Will this compile?
AYes, Integer is a subtype of Number
BNo, ArrayList is not compatible with List
CYes, with warning
DDepends on compiler version
Correct Answer:
B. No, ArrayList is not compatible with List
EXPLANATION
Generics are invariant. ArrayList<Integer> cannot be assigned to List<Number> even though Integer is a subtype of Number. This prevents type safety issues.