为了制作包含值副本而不是引用的数组副本,我执行以下操作:
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/