• Post Reply Bookmark Topic Watch Topic
  • New Topic

new list for each iteration ?  RSS feed

 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is better ?

This:

version 1:


or that:

version 2:


In version 1, I declare a list for each iteration, In version 2, I only declare one list and overwrite it for each iteration - but the overall result is the same. Following the rule "Declare variables as close as possible to where they are used." (http://www.javaranch.com/styleLong.jsp#init), I have to use version 1, but in this case I am not sure.
 
Darryl Burke
Bartender
Posts: 5167
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you're not declaring one list and overwriting it, you're assigning a different List, the one returned from getHobbies(), in both cases. The only difference is that in the second code, the last assigned List is still available after the loop exits.


 
Rob Spoor
Sheriff
Posts: 21092
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which makes it not yet eligible for garbage collection, so unless you still need it after the loop you should declare it inside the loop.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!