java - md 数组的 newarray = oldarray.clone() 究竟有什么问题?

标签 java arrays

在对 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/

相关文章:

java - Spark Java - 如何迭代数据帧 Dataset<Row> 中的行,并将一列的值添加到 Arraylist

java - Spring AOP @AfterThrowing 无法正常工作,错误于::0 切入点中正式未绑定(bind)

java - 有没有办法在 JavaFX 中的不同类文件中使用线程?

c++ - 在同一结构中声明一个结构数组

c++ - 在 C++17 中声明大小为 0 的数组是否合法?

python - 该方法查找数组(python)中的反转次数的时间复杂度是多少?

java - 简单的 Hibernate 映射建议

Java:从 ArrayList<String> 构建 JTree

java - 从字符串数组中查找重复值

javascript - 将 javascript 数组中的重复值分组在一起,然后按值名称升序对这些组进行排序