问题描述
好的,我知道以前有人问过这个问题:上一个问题
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(); }