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 po开发者_JAVA技巧ssible for arraylists also?
You can use Arrays.copyOf
methods.
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.
精彩评论