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

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

问题描述

我有一个名为int的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;
}


推荐答案

有两种好方法可以copy数组是使用clone和 System.arraycopy()

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

以下是如何使用clone for 2D case :

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中复制一个2d数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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