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

查看:335
本文介绍了如何复制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

这篇关于如何复制Java中的二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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