0

Assuming I have a 2-D array as follow:

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. 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:

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. 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.

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.

I wonder if you can help me with this issue? Thanks.

  • How about a for loop within a for loop ! – Erran Morad Apr 30 '14 at 23:14
  • I have a loop. Actually I did not show the whole code here. each time I change 'new_a', it changes automatically 'a' too! – user3586916 Apr 30 '14 at 23:15
  • 2
    possible duplicate of [Make copy of array Java](http://stackoverflow.com/questions/5785745/make-copy-of-array-java) – Asthor Apr 30 '14 at 23:17
  • 1
    You need to copy the array, see [How do I do a deep copy of a 2d array in Java?](http://stackoverflow.com/q/1564832/1347968). But maybe we can help you better if you explain the context a bit more, i.e. why you need to build this `HashMap`. – siegi Apr 30 '14 at 23:18
  • Thanks. 'deep copy'solved the issue. Appreciate your help. – user3586916 May 01 '14 at 00:00

2 Answers2

0

Make sure you are defining double [][] new_a = a and HashMap<Integer,double[][]> Store=new HashMap<Integer,double[][]>()outside of the loop. 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?

Moiety Design
  • 473
  • 4
  • 9
0

Two methods. 2nd is faster, should be O(n), I beleave.

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);
        }
Jakkra
  • 641
  • 8
  • 25