在java中复制一个二维数组 [英] copy a 2d array in java

查看:43
本文介绍了在java中复制一个二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个称为 int 类型的矩阵的二维数组,我想将其复制到方法中的局部变量,以便我可以对其进行编辑

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

复制数组的最佳方法是什么,我遇到了一些麻烦

whats the best way to copy the array, i am having some troubles

例如

    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;
}

推荐答案

复制数组有两种好方法,分别是clone和System.arraycopy().

There are two good ways to copy array is to use clone and System.arraycopy().

以下是如何在 2D 案例中使用克隆:

Here is how to use clone for 2D case:

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

对于 System.arraycopy(),你使用:

For System.arraycopy(), you use:

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);
}

我没有基准,但我可以用我的 2 美分 打赌,它们比自己做更快,更不容易出错.特别是 System.arraycopy() 因为它是在本机代码中实现的.

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. Especially, System.arraycopy() as it is implemented in native code.

希望这会有所帮助.

修复错误.

这篇关于在java中复制一个二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆