Copying a 2D array using .clone() still references

2020-04-11 04:49发布

问题:

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

回答1:

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();
}