Consider the following program:
import java.util.*; class ListFromVarargs { public static <T> List<T> asList1(T... elements) { ArrayList<T> temp = new ArrayList<>(); for(T element : elements) { temp.add(element);/*from w w w . j av a 2 s . c om*/ } 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.