• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

new list for each iteration ?

 
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 5167
11
Netbeans IDE Opera Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.


 
Sheriff
Posts: 22784
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic