Re: Life of an instance
Salad wrote:
I didn't have a specific situation. I was thinking that if one had,
let's say 3 customers to process, if one reused the object cust (like in
a for loop) or if 1 held all three custs, a different instance for each
one.
Either or both work. As Lew says, using "new" and making a new object
rather than reusing one is probably less error prone. There are a few
"large" objects like the ones under Collection or a StringBuilder that
you may wish to explictly clear rather than create anew each time
through a loop. Normally, you'd only decide to do that after
performance testing revealed that calling "new" was a bottleneck.
To process three customers, use an array or Collection:
public Customer[] test2() {
Customer[] custArray = new Customer[3];
for( int i = 0; i < custArray.length; i++ ) {
custArray[i] = new Customer();
// more processing here...
}
return custArray;
}
All three Customer objects remain in scope here because the custArray
object retains references to them. Eric Sosman was explaining this in
his post.
For a Collection of some sort:
public List<Customer> test2() {
ArrayList<Customer> custs = new ArrayList<Customer>();
for( int i = 0; i < 3; i++ ) {
Customer c = new Customer();
custs.add( c );
// more processing here...
}
return custs;
}
Again, these three Customer objects are preserved because the ArrayList
holds a reference to them.