如何在 Java 中复制二维数组? [英] How do I copy a 2 Dimensional array in Java?

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

问题描述

我需要为我正在处理的项目制作一个相当大的二维数组的副本.我有两个二维数组:

int[][]current;int[][]旧;

我也有两种方法可以进行复制.我需要复制数组,因为当前正在定期更新.

public void old(){旧=当前}

public void keepold(){当前=旧}

然而,这行不通.如果我调用old,更新current,然后调用keepold,current 不等于它原来的值.为什么会这样?

谢谢

解决方案

current=oldold=current 使两个数组指向同一个事物,所以如果您随后修改 currentold 也会被修改.要将一个数组的内容复制到另一个数组,请使用 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屋!

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