1

I noticed that in Java that when you pass an array into a function, it modifies the original array. I am trying to implement the backtracking method that uses recursion and I want each call to it to have its own array copying the contents of the array passed in.

For example, say I have an original array and I go through a loop that calls the function. I want each call to have an array that contains everything from the original array, but anything it modifies stays within itself, not modifying the original array. Is this possible?

If there's a solution, would it be possible for arraylists also?

sudo
  • 329
  • 7
  • 14
  • 1
    It's unclear to me whether you're asking about just copying the array so that its contents refer to the same objects -- or actually copying the objects inside of the array themselves. If you mean the former, then Chandra's answer is the right one. However, if you actually want the objects in the array themselves to not be modified, I would highly recommend avoiding Clone. Instead, you should look into making your objects immutable, so modifications create a new instance. – Michael D Nov 20 '10 at 23:18
  • check http://stackoverflow.com/questions/2589741/how-to-effectively-copy-an-array-in-java – Srujan Kumar Gulla Feb 20 '13 at 18:19

2 Answers2

5

You can use Arrays.copyOf methods.

Chandra Patni
  • 17,347
  • 10
  • 55
  • 65
  • 2
    And you can just clone an arraylist – Tom Nov 20 '10 at 23:10
  • I am assuming this is an expensive way to do this. If I wanted to have a recursion method but each call have its own array, would there be another way less expensive then making a new array every time? – sudo Nov 20 '10 at 23:11
  • 1
    @sudo: so you want to copy the array... without copying it? – SimonJ Nov 20 '10 at 23:37
  • @SimonJ he wants a persistent collection. That is, the stuff that is the same in the copies of the arrays is only stored once, and then the differences are stored in each copy. – alternative Nov 20 '10 at 23:48
2

Probably the fastest way to do this in Java will be the System.arraycopy method documented here. It's a native method and is generally as fast as you're going to get.

In certain cases you could try a copy-on-write approach which might help if you are not really modifying the entire array.

Steven Schlansker
  • 37,580
  • 14
  • 81
  • 100
  • 1
    It's worth noting that Arrays.copyOf uses System.arraycopy under the hood, and takes care of the creation of the destination array, so unless you have a pre-existing destination it's less effort to use Arrays.copyOf - though that's only available since 1.6 – earcam Jan 30 '13 at 13:29