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

笑着哭i 提交于 2019-12-01 23:42:05

问题


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


来源:https://stackoverflow.com/questions/8299771/copying-a-2d-array-using-clone-still-references-original-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!