E
Edward A Thompson
I am puzzled by the bahavior of ArrayList process, and was hoping some
could explain...
Given the following code:
Book b = new Book();
ArrayList books = new ArrayList();
for (i=1; i <= 5; i++)
{
b.title = i;
books.add(b);
}
at the end of the loop I have 5 items in the list;
5,5,5,5,5 instead of 1,2,3,4,5.
What is books.add doing? Is it storing a reference, and not an actual
copy of the object? I would have thought I coudl reuse b over and
over.
If I put the instantiation of b inthe loop all is well.
Can someone explain?
could explain...
Given the following code:
Book b = new Book();
ArrayList books = new ArrayList();
for (i=1; i <= 5; i++)
{
b.title = i;
books.add(b);
}
at the end of the loop I have 5 items in the list;
5,5,5,5,5 instead of 1,2,3,4,5.
What is books.add doing? Is it storing a reference, and not an actual
copy of the object? I would have thought I coudl reuse b over and
over.
If I put the instantiation of b inthe loop all is well.
Can someone explain?