Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Is this Generics model answer correct

 
sam Asare
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Studying for SCJP5 using Sierra/Bates book.

In generics end of ch question 16 has the answer as below. However I am not sure its correct.

public static <E extends Number> List<? super E> process(List <E>

//if you want to invoke the method like this
ArrayList<Integer>input=null
List<Integer>output=null

output=process(input)//will this invocation work with the above 2 lines?

//I thought the process method requires a list as input.
 
Scott Johnson
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[sam] I thought the process method requires a list as input.

It does. input "is a" List. (It's an instance of ArrayList which is a subclass of List.)
 
sam Asare
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So =would it work with:

ArrayList<Integer> input=null
ArrayList<Integer>output=null
 
Scott Johnson
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mmmmmm. No.

output should not be defined as an ArrayList. It should be a List.

The return type of the process() method is List so it could return a LinkedList, ArrayList or any other object that implements the List interface.

You can't store a reference to a LinkedList in an ArrayList reference.
 
sam Asare
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks- Your explanation has cleared my confusion
 
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!