我需要为我正在进行的项目制作一个相当大的二维数组的副本。我有两个二维数组:
int[][]current;
int[][]old;
我也有两种方法来进行复制。我需要复制数组,因为 current 会定期更新。
public void old(){
old=current
}
和
public void keepold(){
current=old
}
但是,这不起作用。如果我调用 old,对 current 进行更新,然后调用 keepold,则 current 不等于原来的值。为什么会这样?
谢谢
原文由 badcoder 发布,翻译遵循 CC BY-SA 4.0 许可协议
current=old
orold=current
makes the two array refer to the same thing, so if you subsequently modifycurrent
,old
will be modified too.要将数组的内容复制到另一个数组,请使用 for 循环PS:对于一维数组,您可以避免使用
Arrays.copyOf
创建自己的 for 循环