Deep copy of the 2D-array with all the elements

I make the base game with using 2D-array (4x4), wherein the elements (such as the object numbered 1 to 16) should switch to achieve a certain target state, this state shall be compared with the current state, therefore, the need for copying.

So far, I:

public void cloneArray() throws CloneNotSupportedException { ClassName copy = (ClassName)super.clone(); copy.tiles = (Tile[][]) tiles.clone(); } 

This seems right, or am I missing something?

+4
source share
1 answer

You need to take one more step and do this:

  ClassName copy = (ClassName)super.clone(); copy.tiles = (Tile[][]) tiles.clone(); for(int i = 0; i < copy.tiles.length; i++) { copy.tiles[i] = (Tile[]) tiles[i].clone(); } );  ClassName copy = (ClassName)super.clone(); copy.tiles = (Tile[][]) tiles.clone(); for(int i = 0; i < copy.tiles.length; i++) { copy.tiles[i] = (Tile[]) tiles[i].clone(); } ) tiles.clone ();  ClassName copy = (ClassName)super.clone(); copy.tiles = (Tile[][]) tiles.clone(); for(int i = 0; i < copy.tiles.length; i++) { copy.tiles[i] = (Tile[]) tiles[i].clone(); } {  ClassName copy = (ClassName)super.clone(); copy.tiles = (Tile[][]) tiles.clone(); for(int i = 0; i < copy.tiles.length; i++) { copy.tiles[i] = (Tile[]) tiles[i].clone(); } ]) tiles [i] .clone ();  ClassName copy = (ClassName)super.clone(); copy.tiles = (Tile[][]) tiles.clone(); for(int i = 0; i < copy.tiles.length; i++) { copy.tiles[i] = (Tile[]) tiles[i].clone(); } 

The reason is that the clone creates a shallow copy of the top-level array that holds links to other arrays.

+3
source

All Articles