android - 按值复制数组失败(使用 clone() 或 arraycopy())(Android、Java)

标签 android clone arrays

为了制作包含值副本而不是引用的数组副本,我执行以下操作:

int[][][] copy = {{{0}},{{0}},{{0,0}},{{0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0}},{{0}},{{0,0}}};
System.arraycopy(spelerSpel, 0, copy, 0, spelerSpel.length);

然后在副本中更改一个值:

copy[SPELER_NUMMER][0][0] = baanSpelerNummer;

此时原始 (spelerSpel) 数组中的结果保持相同的更改值,例如:

{{{4}},{{0}},{{0,0}},{{0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0}},{{0}},{{0,0}}};

作为副本。我也尝试了 .clone(),结果相同。我做错了什么?

顺便说一下,我的目标是 Android API 8,它不支持 Arrays.copyOf()。

最佳答案

System.arraycopy() 不支持深度复制,但它在简单数组的性能方面做得很好。

您可以将它与一些额外的循环一起使用来创建您自己的多维 arraycopy3d():

public int[][][] arraycopy3d(int[][][] array) {

     int[][][] copy = new int[array.length][][];

     for (int i = 0; i < array.length; i++) {
         copy[i] = new int[array[i].length][];
         for (int j = 0; j < array[i].length; j++) {
             copy[i][j] = new int[array[i][j].length];
             System.arraycopy(array[i][j], 0, copy[i][j], 0, array[i][j].length);
        }
    }

    return copy;
} 

关于android - 按值复制数组失败(使用 clone() 或 arraycopy())(Android、Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14695456/

相关文章:

android - 自动关闭 chrome 自定义标签

android - 键盘打开时,带有 fragment 的 Activity 不会调整大小

java - 从 Firebase 中嵌套保存的数据中检索数据

jquery - ReplaceWith() 不适用于克隆的、分离的节点

javascript - 在 JavaScript 中复制数组的最快方法 - 切片与 'for' 循环

java - 当编辑文本焦点发生变化时,如何在特定时间间隔(约 120 秒)后自动保存

php - 克隆问题 - jquery/php

GWT Overlay 深拷贝

C - 在数组中使用字符串

c++ - 数组作为 ValueSet 中的值