简体   繁体   English

在java中复制一个二维数组

[英]copy a 2d array in java

i have a 2d array called matrix of type int that i want to copy to a local variable in a method so i can edit it我有一个称为 int 类型的矩阵的二维数组,我想将其复制到方法中的局部变量,以便我可以对其进行编辑

whats the best way to copy the array, i am having some troubles复制数组的最佳方法是什么,我遇到了一些麻烦

for example例如

    int [][] myInt;
    for(int i = 0; i< matrix.length; i++){
        for (int j = 0; j < matrix[i].length; j++){
            myInt[i][j] = matrix[i][j];
        }
    }

    //do some stuff here
    return true;
}

There are two good ways to copy array is to use clone and System.arraycopy() .有两种复制数组的好方法是使用 clone 和System.arraycopy()

Here is how to use clone for 2D case:以下是如何将克隆用于 2D 案例:

int [][] myInt = new int[matrix.length][];
for(int i = 0; i < matrix.length; i++)
    myInt[i] = matrix[i].clone();

For System.arraycopy(), you use:对于 System.arraycopy(),您使用:

int [][] myInt = new int[matrix.length][];
for(int i = 0; i < matrix.length; i++)
{
  int[] aMatrix = matrix[i];
  int   aLength = aMatrix.length;
  myInt[i] = new int[aLength];
  System.arraycopy(aMatrix, 0, myInt[i], 0, aLength);
}

I don't have a benchmark but I can bet with my 2 cents that they are faster and less mistake-prone than doing it yourself.我没有基准,但我可以用我的2 美分打赌,它们比自己做更快,更不容易出错 Especially, System.arraycopy() as it is implemented in native code.特别是System.arraycopy()因为它是在本机代码中实现的。

Hope this helps.希望这可以帮助。

Edit: fixed bug.编辑:修复了错误。

It is possible to use streams in Java 8 to copy a 2D array.可以在 Java 8 中使用流来复制二维数组。

@Test
public void testCopy2DArray() {
   int[][] data = {{1, 2}, {3, 4}};
   int[][] dataCopy = Arrays.stream(data)
             .map((int[] row) -> row.clone())
             .toArray((int length) -> new int[length][]);

   assertNotSame(data, dataCopy);
   assertNotSame(data[0], dataCopy[0]);
   assertNotSame(data[1], dataCopy[1]);

   dataCopy[0][1] = 5;
   assertEquals(2, data[0][1]);
   assertEquals(5, dataCopy[0][1]);
}

You are not initializing the local 2D array.您没有初始化本地二维数组。

int[][] myInt = new int[matrix.length][];
for(int i = 0; i < matrix.length; i++)
{
  myInt[i] = new int[matrix[i].length];
  for (int j = 0; j < matrix[i].length; j++)
  {
    myInt[i][j] = matrix[i][j];
  }
}

If the data is large you should consider using a proper linear algebra library like colt or nd4j .如果数据很大,您应该考虑使用合适的线性代数库,如coltnd4j System.arraycopy will likely only be meaningfully faster if the array were single dimensional.如果数组是一维的, System.arraycopy可能只会更快。 Otherwise it can not copy the entire data as one unit and then reshape it as in numpy or R.否则它无法将整个数据复制为一个单元,然后像在 numpy 或 R 中那样对其进行整形。

你也可以这样编码 myInt = matrix.clone();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM