• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics - Chapter 7 Question 8 page 653

 
Glen Iris
Ranch Hand
Posts: 172
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given a method declared as

A programmer wants to use the method like this:

Which pair of declarations could be placed at //INSERT CODE HERE to allow the code to compile?

I understand why A, B, C and G are incorrect.

I understand why E and F are correct.

I do not understand why using D is correct.

D:

Why is it ok for the method to declare that it will accept a list - and the accept an ArrayList
When it is not ok for the return type to declare as a List but not return an ArrayList?

thanks
 
Anayonkar Shivalkar
Bartender
Posts: 1557
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Glen Iris wrote:I do not understand why using D is correct.

Well, I've not seen the other options yet, but as per code, below things are clear:
1) method accepts List of type E
2) method returns List of type E
3) E must be IS-A Number

Option D satisfies all these requirements.

Glen Iris wrote:Why is it ok for the method to declare that it will accept a list - and the accept an ArrayList

because, ArrayList IS-A List.
Glen Iris wrote:When it is not ok for the return type to declare as a List but not return an ArrayList?

if return type is List, method must return something which IS-A list.

I hope this helps.
 
Helen Ma
Ranch Hand
Posts: 451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
List is an interface implemented by ArrayList. ArrayList is a List.
Therefore, you can pass an ArrayList as the argument. List<Integer> list = new ArrayList<Integer>() ; // compiles.
I hope this can help answer your question.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic