如何在 Java 中复制二维数组? [英] How do I copy a 2 Dimensional array in Java?
问题描述
我需要为我正在处理的项目制作一个相当大的二维数组的副本.我有两个二维数组:
int[][]current;int[][]旧;
我也有两种方法可以进行复制.我需要复制数组,因为当前正在定期更新.
public void old(){旧=当前}
和
public void keepold(){当前=旧}
然而,这行不通.如果我调用old,更新current,然后调用keepold,current 不等于它原来的值.为什么会这样?
谢谢
current=old
或 old=current
使两个数组指向同一个事物,所以如果您随后修改 current
,old
也会被修改.要将一个数组的内容复制到另一个数组,请使用 for 循环
for(int i=0; i
PS:对于一维数组,您可以使用 Arrays.copyOf
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
}
and
public void keepold(){
current=old
}
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?
Thanks
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: For a one-dimensional array, you can avoid creating your own for loop by using Arrays.copyOf
这篇关于如何在 Java 中复制二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!