Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java polymorphism confusion

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

like image 314
msharma Avatar asked May 13 '09 15:05

msharma


3 Answers

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.

like image 200
starblue Avatar answered Oct 04 '22 23:10

starblue


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 Lists.

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.

like image 22
coobird Avatar answered Oct 04 '22 21:10

coobird


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.

like image 44
Tim Avatar answered Oct 04 '22 21:10

Tim