Copying a 2D array using .clone() still references original data(使用 .clone() 复制二维数组仍然引用原始数据)
问题描述
好的,我知道以前有人问过这个问题:上一个问题
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();
}
这篇关于使用 .clone() 复制二维数组仍然引用原始数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 .clone() 复制二维数组仍然引用原始数据
基础教程推荐
- Maven:无效的目标版本:10 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- JPA惰性列表上的流 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
