aspose file tools*
The moose likes Beginning Java and the fly likes Regarding behaviour of arraylist. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Regarding behaviour of arraylist." Watch "Regarding behaviour of arraylist." New topic
Author

Regarding behaviour of arraylist.

arien beck
Greenhorn

Joined: Sep 29, 2011
Posts: 2
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

+++ajaypadvi@gmail.com
+++ajay...padvi@gmail.com
ajaypadvi@gmail.com
ajay...padvi@gmail.com


Please explain this behaviour of arraylist and provide some thoughts regarding this.




Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8396
    
  23

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?
Articles by Winston can be found here
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3742
    
  16
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://aspose.com/file-tools
 
subject: Regarding behaviour of arraylist.