Java – use Clone() copies the 2D array and still references the original data

OK, I know I've asked this question before: previous question

I also studied several other topics and websites, which seem to create more questions than answers

Josh Bloch on design – discussion Clone ();

But I still can't solve my problem

When I clone my 2D array:

values = Map.mapValues.clone();

I still can't safely modify the content of the value because it still modifies the map The contents of mapvalues

Is there any way to copy a more efficient array than I do, just recreate one from scratch each time?

thank you

Solution

In Java, a 2D array is a reference array to a one - dimensional array Map. mapValues. Clone () only clones the first layer (i.e. reference), so it will eventually get a new reference array to the same underlying 1D array That's why your attempt to use clone () doesn't work

One way to solve this problem is to clone the underlying 1D array:

byte[][] values = Map.mapValues.clone();
for (int i = 0; i < values.length; i++) {
  values[i] = values[i].clone();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>