The question below is from Java SCJP5 book by Kathy Sierra and Bert Bates.
Given a method declared as:
public static <E extends Number> List<E> process(List<E> nums)
A programmer wants to use the method like this:
// INSERT DECLARATIONS HERE
output = process(input);
Which pair of declarations could be placed at // INSERT DECLARATIONS HERE to allow the code to compile? (Choose all that apply.)
A.
ArrayList<Integer> input = null;
ArrayList<Integer> output = null;
B.
ArrayList<Integer> input = null;
List<Integer> output = null;
C.
ArrayList<Integer> input = null;
List<Number> output = null;
D.
List<Number> input = null;
ArrayList<Integer> output = null;
E.
List<Number> input = null;
List<Number> output = null;
F.
List<Integer> input = null;
List<Integer> output = null;
G. None of the above.
Correct Answers given are: B, E, F and the explanation in the book states:
“The return type is definitely declared as List, NOT ArrayList so A,D are wrong. ……”
This is what I don’t get…why it is that the return type MUST be List only and not ArrayList?? Just like the argument can be ArrayList then why cant return type also be arrayList?
Thanks
This is actually not specific to generics, but deals with types.
Easy way to think of it is, an
ArrayListis aList, but anListis not necessarily anArrayList.ArrayListimplements theListinterface, so it can be treated as aList. However, just because something implementsList, it is not anArrayList. For example,LinkedListimplementsList, but is not anArrayList.For example the following are allowed:
This is because both
ArrayListandLinkedListboth implement theListinterface, so they both can be handled asLists.However, the following is not allowed:
Although both
ArrayListandLinkedListimplementList, they are not the same class. They may have similarities by implementing the methods ofList, but they are completely separate classes.