File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/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 JavaScript Promises Essentials this week in the JavaScript 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: 61598
    
  67

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: 61598
    
  67

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