如何复制Java中的二维数组? [英] How do I copy a 2 Dimensional array in Java?
问题描述
我需要一个相当大的二维数组的副本的一个项目我工作。我有两个二维数组:
I need to make a copy of a fairly large 2 dimensional array for a project I am working on. I have two 2D arrays:
int[][]current;
int[][]old;
我也有两种方法来进行复制。我需要阵列复制,因为电流是定期更新。
I also have two methods to do the copying. I need to copy the array because current is regularly being updated.
public void old(){
old=current
}
和
public void keepold(){
current=old
}
但是,这是行不通的。如果我叫老了,就目前的更新,然后调用keepold,目前并不等于它原是。为什么会这样呢?
However, this does not work. If I were to call old, make an update on current, and then call keepold, current is not equal to what it was originally. Why would this be?
感谢
推荐答案
电流=旧
或旧=电流
使得两阵列指的是同样的事情,所以如果你在以后修改电流
,老
也将被修改。在磁盘阵列中的内容复制到另一个阵列,使用循环
current=old
or old=current
makes the two array refer to the same thing, so if you subsequently modify current
, old
will be modified too. To copy the content of an array to another array, use the for loop
for(int i=0; i<old.length; i++)
for(int j=0; j<old[i].length; j++)
old[i][j]=current[i][j];
PS:对于一维数组,您可以使用<一个避免创建你自己的循环href=\"http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html\"><$c$c>Arrays.copyOf$c$c>
这篇关于如何复制Java中的二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!