[[-6, 3, 9], [-7, 2, 9], [-3, 2, 5], ... , [3, 4, 1]]
我正在使用的数组的结构与上面的类似。
我的目标是根据之前确定的某个位置来划分这个数组。
我已经尝试过Arrays.copyOf
, Arrays.copyOfRange
,和System.arraycopy
- 但还没有经历过成功,这就是为什么我为此编写了自己的方法;它也不起作用。
partitionResult
是 int
类型的实例(变量)数组结构就像 arrayOfVals
arrayOfVals
似乎用整个 partitionResult
进行了初始化尽管我只想复制一部分。我已经测试过,即 System.out.println (partitionResult[begin+i][j])
,并且打印的值是根据需要的。
private int[][] copyArray(int begin, int end)
{
int SUBARRAY_SIZE = 2;
// below the '+1' is due to zero-indexing
int[][] arrayOfVals = new int[end-begin+1][SUBARRAY_SIZE+1];
end -= begin;
for (int i = 0; i <= end; i++) {
for (int j = 0; j <= SUBARRAY_SIZE; j++) {
arrayOfVals[begin][j] = partitionResult[begin+i][j];
}
}
return arrayOfVals;
}
为什么我不能按照预期执行以下操作?
private void foo(int begin)
{
int[][] arrayOne = copyArray(0, begin);
int[][] arrayTwo = copyArray(begin+1, partitionResult.length -1);
...
}
编辑:
[[-6, 3, 9], [-7, 2, 9], [-3, 2, 5], [3, 4, 1], [0, 5, 5], [2, 3, 1], [3, 4, 1]]
这是我的测试数组。
我想使用copyArray
分割这个数组定义位置的方法 begin
.
当我打印我想要复制的值时,partitionResult[begin+i][j]
,结果完全符合预期;但是,显示最终的 arrayOfVals
- 输出不是我打印的,它是整个 partitionResult
数组。
我要arrayOne
等于 [[-6, 3, 9], [-7, 2, 9], [-3, 2, 5]]
和arrayTwo
等于 [[3, 4, 1], [0, 5, 5], [2, 3, 1], [3, 4, 1]]
编辑2:问题不在于方法 copyArray
但用另一种方法。
toString
我编写的方法显示实例变量 partitionResult
使用的值而不是我传递给它的数组 - 这使得看起来好像没有复制任何内容。这个错误对我来说应该是显而易见的。我非常感谢您的建议。
不过,@Andrea 发现了一个小错误。
最佳答案
这应该很简单,您只是通过改变 end
让自己变得困难,从而难以理解循环的进展。只需复制 begin
和 end
(含)之间的值,但请确保克隆每个子数组。 (克隆有效地取代了您的内部循环。)
private int[][] copyArray(int begin, int end) {
// Calculate the size of the output
// below the '+1' is due to zero-indexing
int size = end - begin + 1;
int[][] arrayOfVals = new int[size][];
for (int i = 0; i < size; i++) {
// Clone each subarray to make sure changes to the copy
// don't affect the internal array
// (A shallow .clone() suffices for integer arrays)
arrayOfVals[i] = partitionResult[begin + i].clone();
}
return arrayOfVals;
}
这会在调用 foo(2)
时给出示例输入的预期输出。
关于java - java中数组的部分复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18640474/