Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

returning a generic collection

 
Rachel Glenn
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 65105
89
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rachel Glenn
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 65105
89
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Correct. All anyone calling the method needs to know is that it is an implementation of List. Which one is moot.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic