This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Java in General and the fly likes How to pass arraylist in methods? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Java » Java in General
Bookmark "How to pass arraylist in methods?" Watch "How to pass arraylist in methods?" New topic

How to pass arraylist in methods?

Sandeep Kumar B
Ranch Hand

Joined: Jul 10, 2011
Posts: 45
So, here is my program which is not giving me expected output.
Can someone please explain?

Class file

Test class

Output is

I was expecting to get modified list with ID's as 1,2,3, etc in main method but its not happening
Any idea why?
John Vorwald
Ranch Hand

Joined: Sep 26, 2010
Posts: 139
You only made one object, and then added it 20 times, and kept changing the values in the one object. When you print it, you get the last values set. You need to create new objects in the loop.



For the 2nd option, you could make a copy constructor method.
I agree. Here's the link:
subject: How to pass arraylist in methods?
jQuery in Action, 3rd edition