复制使用.clone()的二维数组仍然引用原始数据 [英] Copying a 2D array using .clone() still references original data
问题描述
好吧,我知道这个问题已经前已问: previous问题
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.
乔希布洛赫的设计 - 文章讨论 .clone ();
但我仍然不能回答摸出我的问题。
But I still couldn't work out the answer to my problem.
当我克隆我的二维数组:
When I clone my 2D array:
values = Map.mapValues.clone();
我仍然无法安全地修改值的含量
因为它仍然修改的内容 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();
}
这篇关于复制使用.clone()的二维数组仍然引用原始数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!