简体   繁体   English

如何在Java中制作二维数组的副本?

[英]How can I make a copy of 2-D array in java?

Assuming I have a 2-D array as follow: 假设我有一个二维数组,如下所示:

double[][] a={{1,0,0},{0,0,1},{0,1,0}}; double [] [] a = {{1,0,0},{0,0,1},{0,1,0}};

I need to use this 'a' in a loop, each time as an input of a method. 我每次都需要在循环中使用此“ a”作为方法的输入。 According to the output of the method, one element of this 2-D array may change. 根据该方法的输出,此二维数组的一个元素可能会更改。 for example: 例如:

double [][] new_a=a;
new_a[0][0]=0;

I want to store the new-a in a Hash-map: 我想将new-a存储在哈希图中:

HashMap<Integer,double[][]> Store=new HashMap<Integer,double[][]>();
Store.put(size.Store(),new_a);

next time in the loop I need the original 'a' though. 下次在循环中我需要原始的“ a”。 I don't know how I can make a copy from 2-D array 'a' in order to use the original one each time in the loop and store the new one in the Hash-map. 我不知道如何从二维数组'a'中复制一个副本,以便每次在循环中使用原始副本并将新副本存储在哈希图中。

When I coded like above it changes the original 'a' as well and when I want to store in 'Store' it replaces new_a for all previous stored arrays. 当我像上面那样编码时,它也会更改原始的“ a”,并且当我想存储在“ Store”中时,它将所有先前存储的数组替换为new_a。

I wonder if you can help me with this issue? 我想知道您是否可以帮助我解决这个问题? Thanks. 谢谢。

Make sure you are defining double [][] new_a = a and HashMap<Integer,double[][]> Store=new HashMap<Integer,double[][]>() outside of the loop. 确保在double [][] new_a = a定义double [][] new_a = aHashMap<Integer,double[][]> Store=new HashMap<Integer,double[][]>() I think that may be your problem that you are redefining everything in the loop. 我认为这可能是您在重新定义循环中的所有内容时遇到的问题。 Can you show an extended version of your code to see the loop itself? 您可以显示代码的扩展版本以查看循环本身吗?

Two methods. 两种方法。 2nd is faster, should be O(n), I beleave. 第二快,应该是O(n),我相信。

for(int i=0; i<old.length; i++)
  for(int j=0; j<old[i].length; j++)
    old[i][j]=current[i][j];

or 要么

 int[][] src //Old one you want a copy of
    int length = src.length;
        int[][] target = new int[length][src[0].length];
        for (int i = 0; i < length; i++) {
            System.arraycopy(src[i], 0, target[i], 0, src[i].length);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM