What will be printed when the program is compiled and run?
public class Main { public static void main(String[] args) { Object obj = new ArrayList<Integer>(); // (1) List<?> list1 = (List<?>) obj; // (2) List<?> list2 = (List) obj; // (3) List list3 = (List<?>) obj; // (4) List<Integer> list4 = (List) obj; // (5) List<Integer> list5 = (List<Integer>) obj; // (6) }/*from w ww . java 2 s . co m*/ }
Select the one correct answer.
(d)
Casts are permitted, as in (2)-(6), but can result in an unchecked warning.
The assignment in (5) is from a raw type (List) to a parameterized type (List<Integer>), resulting in an unchecked assignment conversion warning.
Note that in (5) the cast does not pose any problem.
It is the assignment from generic code to legacy code that can be a potential problem, flagged as an unchecked warning.
In (6), the cast is against the erasure of List<Integer>, that is to say, List.
The compiler cannot guarantee that obj is a List<Integer> at runtime, it therefore flags the cast with an unchecked warning.