使用 .clone() 复制二维数组仍然引用原始数据

2022-01-20 00:00:00 复制 arrays clone java

好的,我知道以前有人问过这个问题:上一个问题

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 谈设计 - 一篇讨论 .clone() 的文章;

但我仍然无法解决我的问题.

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

当我克隆我的二维数组时:

When I clone my 2D array:

values = Map.mapValues.clone();

我仍然不能安全地修改 values 的内容,因为它仍然会修改 Map.mapValues 的内容.

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?

谢谢

推荐答案

在 Java 中,二维数组是一维数组的引用数组.Map.mapValues.clone() 只克隆第一层(即引用),因此您最终会得到一个新的引用数组,以相同的底层一维数组.这就是您尝试使用 clone() 失败的原因.

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

相关文章