java - java中数组的部分复制

标签 java arrays

[[-6, 3, 9], [-7, 2, 9], [-3, 2, 5], ... , [3, 4, 1]]

我正在使用的数组的结构与上面的类似。

我的目标是根据之前确定的某个位置来划分这个数组。

我已经尝试过Arrays.copyOf , Arrays.copyOfRange ,和System.arraycopy - 但还没有经历过成功,这就是为什么我为此编写了自己的方法;它也不起作用。

partitionResultint 类型的实例(变量)数组结构就像 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 让自己变得困难,从而难以理解循环的进展。只需复制 beginend(含)之间的值,但请确保克隆每个子数组。 (克隆有效地取代了您的内部循环。)

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/

相关文章:

返回 javax.ws.rs.core.Response 对象的 Java JMX 调用方法不起作用(获取 NotSerializedException)

javascript - 带有 Request.Form 的 JScript 数组

ios - NSPredicate 在 NSArray 上搜索任何对象

javascript - 如何检查 promise 是否已解决并有条件地呈现 Javascript?

c++ - 似乎无法让我的结构数组正确排序?

javascript - 如何在 JavaScript 中过滤和映射数组

java - java 中的多线程 - 4 个线程自动执行相同的操作

java - 对象数组内存分配(堆栈和堆)

java - JSF 2.2 表单上的 tagmanager.js 不起作用。我究竟做错了什么?

Java 流 |在 .map() 或 .forEach() 之后产生重复记录