3

Okay, I know this question has been asked before: Previous Question

I have also looked into a few other threads and websites and they all seem to create more questions than answers.

Josh Bloch on Design - an article discussing .clone();

But I still couldn't work out the answer to my problem.

When I clone my 2D array:

values = Map.mapValues.clone();

I still cannot safely modify the content of values as it still modifies the content of Map.mapValues.

Is there actually a way to copy an array which is more efficient than me just re-creating one from scratch each time?

Thanks

Community
  • 1
  • 1
Troyseph
  • 4,960
  • 3
  • 38
  • 61

1 Answers1

7

In Java, a 2D array is an array of references to 1D arrays. Map.mapValues.clone() only clones the first layer (i.e. the references), so you end up with a new array of references to the same underlying 1D arrays. This is why your attempt to use clone() did not work.

One way to fix this is by also cloning the underlying 1D arrays:

byte[][] values = Map.mapValues.clone();
for (int i = 0; i < values.length; i++) {
  values[i] = values[i].clone();
}
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Thank you, this fixes my problem, is there a different method I could call which doesn't involve using a for(;;) loop? – Troyseph Nov 28 '11 at 17:43
  • @SebastianTroy: I don't know of any function in the standard library that would do this. I personally would turn the four lines of code into a helper function that can be invoked as needed. – NPE Nov 28 '11 at 17:46
  • Hi, I've been cleaning up my old questions, tried to keep your answer valid, just in case you wanted to check... – Troyseph Jan 27 '15 at 10:32