在java中复制一个二维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1686425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
copy a 2d array in java
提问by roberto duran
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;
}
回答by Amarghosh
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];
}
}
回答by NawaMan
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 centsthat they are faster and less mistake-pronethan doing it yourself. Especially, System.arraycopy()
as it is implemented in native code.
我没有基准,但我可以用我的2 美分打赌,它们比自己做更快,更不容易出错。特别是,System.arraycopy()
因为它是在本机代码中实现的。
Hope this helps.
希望这可以帮助。
Edit: fixed bug.
编辑:修复了错误。
回答by valli
you can code like this also myInt = matrix.clone();
你也可以这样编码 myInt = matrix.clone();
回答by NickF
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]);
}