Friday, 18 November 2016

java - Passing ArrayList as a parameter



Let me start by saying that I can't put any code here because Internet on my laptop is not working so I am posting this through my phone. Okay the problem is that say I have two classes: class one and two. Class one has an ArrayList as one of its attributes and it calls a void method from class two and passes that ArrayList as a parameter. Now that method initializes another ArrayList and makes it equal to the parameter passed by me and makes changes to that new ArrayList. Funny thing is that even my original ArrayList which was passed as parameter is also changing. What could be the possible reason?


Answer



The problem is that when you use = to make the new ArrayList a copy of the original, you're just creating a new reference to the same ArrayList. Think of it as two variables pointing at the same object.



Check this out, it might help you understand what's happening: Is Java "pass-by-reference" or "pass-by-value"?




In order to solve your problem, you need to create a new ArrayList by using the "new" keyword and then adding all of the objects, or use the clone() method.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...