Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to pass arraylist in methods?

 
Sandeep Kumar B
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

either


or


For the 2nd option, you could make a copy constructor method.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic