在对 java 中多维数组操作的复制进行一些搜索后,我发现了这个问题:copy a 2d array in java一个被否决的答案建议使用标题中的方法。所以我的问题是:
1) 为什么不好? (因为它看起来又快又明显)
2) 最好的方法还是System.arraycopy
每行?
最佳答案
从根本上说,数组是一个对象。如果您有一个多维数组并克隆它,您将不会获得内部数组的副本(因为它们也是数组 Object
(s))。你可以使用 Arrays.copyOf(T[],int)
.从链接的 Javadoc,
Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain null. Such indices will exist if and only if the specified length is greater than that of the original array. The resulting array is of exactly the same class as the original array.
编辑
上面的代码类似于 System.arraycopy()
但也创建了 shallow copies .如果需要创建deep copies对于多维数组,您必须遍历数组克隆并为每一行创建一个深拷贝。
关于java - md 数组的 newarray = oldarray.clone() 究竟有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26453100/