aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes returning a generic collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "returning a generic collection" Watch "returning a generic collection" New topic
Author

returning a generic collection

Rachel Glenn
Ranch Hand

Joined: Oct 24, 2012
Posts: 95
Suppose I have a function as follows:


Why can't I declare the variable output as an ArrayList<Integer> ? Why must it be declared as List<Integer> in order for it to compile?

Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60046
    
  65

Because that's what the method returns. How can the compiler be sure that it will be any particular List implementation? It's not going to peek into the method to see what's actually being created.

P.S. The parameter should also be declared as a List unless there's a very good reason it has to be an ArrayList implementation.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Rachel Glenn
Ranch Hand

Joined: Oct 24, 2012
Posts: 95
ok I see. Because the function could have actually created a LinkedList<Integer>, and so by declaring the output variable as List<Integer>, it would be handled correctly.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60046
    
  65

Correct. All anyone calling the method needs to know is that it is an implementation of List. Which one is moot.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: returning a generic collection
 
Similar Threads
Generics Question
doubt abt Generics mock question - from K&B
Doubt on a K & B SCJP5 guide question: GENERICS
Generics and Collections
S&B 1.5 Chapter 7, question 16