Hello all;
I am trying to run below code which produces an output as shown following the code sample
Output
======
Please note that before adding "test" object to arraylist if I try to print an email field it produces correct output as shown by first two lines in output above.But I dont understands why fields are same if I try to retrieve those individually from arraylist after for loop.
And if I initialize test object within for loop like below
It gives me desired output showing different emails in test each object in arraylist like below
arien beck wrote:Please note that before adding "test" object to arraylist if I try to print an email field it produces correct output as shown by first two lines in output above.But I dont understands why fields are same if I try to retrieve those individually from arraylist after for loop.
Because the two entries in your list point to the same Test object; so what you see will be whatever you last updated it to.
Winston
Isn't it funny how there's always time and money enough to do it WRONG?
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
9
posted
0
You don't add objects to Lists in java, you add references to objects. So in the first code you create a Test object and add a reference to it to the list. You now have two references to that one Test object - the one you created on line 12 and the one you added to the list. You then modify this object and add a second reference to it to the list - you now have three references to one object and this object will contain the data you added the second time thru the loop.
In the second piece of code, you craete a new Test object inside the loop, therefore you will create two Test object (each containing different data) and the list will contain two references - one to each of the two objects.
Does that help ?
Joanne
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.