Passing ArrayList as value only and not reference

fvgs picture fvgs · Apr 3, 2013 · Viewed 52.7k times · Source

Simply put, I have a method with an ArrayList parameter. In the method I modify the contents of the ArrayList for purposes relevant only to what is returned by the method. Therefore, I do not want the ArrayList which is being passed as the parameter to be affected at all (i.e. not passed as a reference).

Everything I have tried has failed to achieve the desired effect. What do I need to do so that I can make use of a copy of the ArrayList within the method only, but not have it change the actual variable?

Answer

Avi picture Avi · Apr 3, 2013

Even if you had a way to pass the array list as a copy and not by reference it would have been only a shallow copy.

I would do something like:

void foo(final ArrayList list) {

    ArrayList listCopy = new ArrayList(list);
    // Rest of the code

}

And just work on the copied list.