-1

I have function to deep copy a board of squares:

public Square[][] copy_array(Square[][] board) {

    Square[][] nv = new Square[8][8];
    for (int i = 0; i < nv.length; i++)
        nv[i] = Arrays.copyOf(board[i], board[i].length);

    return nv;
}

when I use this function and make changes to nv, it makes a change to the original board[][] square that I pass in. I read that Arrays.copyOf returns a cloned array that is unaffected by changes to the original. but this does not work the other way round, like the example above. the memory reference in source array is just pointed to the new location as per: Does Arrays.copyOf produce a shallow or a deep copy?

what would be the best way to do a true deep copy so that changes to the objects in nv do not change the objects in board?

entercaspa
  • 674
  • 2
  • 7
  • 19
  • Look at options here: https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript – Aragorn Nov 05 '18 at 14:14
  • 3
    that is javascript, son of arathorn, i require java! – entercaspa Nov 05 '18 at 14:15
  • 1
    Oh, where's my coffee this morning lol – Aragorn Nov 05 '18 at 14:16
  • 1
    If you need copies of each of your `Square` instances, then you should provide some way of copying them in the `Square` class, such as a copy constructor. – khelwood Nov 05 '18 at 14:17
  • @entercaspa, are the objects serializable? you could use JAXB or something like that to serialize and de-serialize the array – Aragorn Nov 05 '18 at 14:17

1 Answers1

0

Try to use something like this

public Square[][] copy_array(Square[][] board) {

    Square[][] nv = new Square[8][8];
    for (int i = 0; i < nv.length; i++)
        nv[i] = board[i].clone();

    return nv;
}

I didn't test it but clone makes a deep copy

Apuna12
  • 375
  • 2
  • 6
  • 23