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
Because ArrayList is a subclass of List, so the List returned by process is not guaranteed to be an ArrayList. For example, it could be a LinkedList instead.
This is actually not specific to generics, but deals with types.
Easy way to think of it is, an ArrayList
is a List
, but an List
is not necessarily an ArrayList
.
ArrayList
implements the List
interface, so it can be treated as a List
. However, just because something implements List
, it is not an ArrayList
. For example, LinkedList
implements List
, but is not an ArrayList
.
For example the following are allowed:
List arrayList = new ArrayList();
List linkedList = new LinkedList();
This is because both ArrayList
and LinkedList
both implement the List
interface, so they both can be handled as List
s.
However, the following is not allowed:
ArrayList arrayList = new LinkedList();
Although both ArrayList
and LinkedList
implement List
, they are not the same class. They may have similarities by implementing the methods of List
, but they are completely separate classes.
When you specify a return of type List, you're saying that the return can be any kind of List, whether it be an ArrayList, LinkedList, or other kind of List. If you try to return an ArrayList, you're being too specific - it's no longer a generic List.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With