Two Laptop Bag
The moose likes Beginning Java and the fly likes new list for each iteration ? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "new list for each iteration ?" Watch "new list for each iteration ?" New topic
Author

new list for each iteration ?

nimo frey
Ranch Hand

Joined: Jun 28, 2008
Posts: 580
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

Joined: May 03, 2008
Posts: 4165
    
    3

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.



luck, db
There are no new questions, but there may be new answers.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19216

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.


SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: new list for each iteration ?
 
Similar Threads
Understanding @XmlElementRef in JAXB
query results into new ArrayList or not?
Variable declaration inside loops - what happens?
generic casting with object.getClass() ?
Simple J2SE 5.0 Tiger Notes