Consider the following program:
import java.util.ArrayList; import java.util.List; class ListFromVarargs { public static <T> List<T> asList1(T... elements) { ArrayList<T> temp = new ArrayList<>(); for (T element : elements) { temp.add(element);/* w w w . jav a2s. c o m*/ } return temp; } public static <T> List<?> asList2(T... elements) { ArrayList<?> temp = new ArrayList<>(); for (T element : elements) { temp.add(element); } return temp; } public static <T> List<?> asList3(T... elements) { ArrayList<T> temp = new ArrayList<>(); for (T element : elements) { temp.add(element); } return temp; } public static <T> List<?> asList4(T... elements) { List<T> temp = new ArrayList<T>(); for (T element : elements) { temp.add(element); } return temp; } }
Which of the asList()
definitions in this program will result in a compiler error?
a)The definition of asList1 will result in a compiler error. b)The definition of asList2 will result in a compiler error. c)The definition of asList3 will result in a compiler error. d)The definition of asList4 will result in a compiler error. e)None of the definitions (asList1, asList2, asList3, asList4) will result in a compiler error.
b)
In the asList2
method definition, temp is declared as ArrayList<?>.
Since the template type is a wild-card, you cannot put any element (or modify the container).
Hence, the method call temp.add(element); will result in a compiler error.