sudo
sudo

Reputation: 329

Efficient way to copy arrays and arraylists?

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?

Upvotes: 1

Views: 2227

Answers (2)

Steven Schlansker
Steven Schlansker

Reputation: 38526

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.

Upvotes: 2

Chandra Patni
Chandra Patni

Reputation: 17577

You can use Arrays.copyOf methods.

Upvotes: 5

Related Questions