2

I'm working with an int[n][n] board:

0 2 3 4 1 5 7 8 6 

I want to make a copy called twin, then return the modified copy.

For example:

 int [][] twin = board.clone(); twin[0][0] = board[0][1]; twin[0][1] = board[0][0]; return twin; 

What I expected is:

//board 0 2 3 4 1 5 7 8 6 //twin 2 0 3 4 1 5 7 8 6 

But the result is:

//board 2 2 3 4 1 5 7 8 6 //twin 2 2 3 4 1 5 7 8 6 

The board and twin were the same all along and the clone was not working as expected. Is it because int[][] is not an object?

Is there a way to clone int[][] and modify the way I was expecting? Should I loop over board and copy the values to twin?

1

2 Answers 2

6

First, an array is not a primitive type; it's an object. Second, multidimensional arrays are implemented as arrays of arrays. Also, the clone method for arrays is shallow. When you clone a multi-dimensional array, your new multidimensional array still refers back to the original internal arrays.

board -> [ . . . ] | | | v v v [0, 2, 3], [4, 1, 5], [7, 8, 6] ^ ^ ^ | | | twin -> [ . . . ] 

So when you modify the values, you're not copying from two different arrays, you're copying from the same array, which is why you wind up with [2, 2, 3].

If you're going to clone a multidimensional array, you'll need to clone all the way down to the one-dimensional arrays also.

int [][] twin = board.clone(); for (int i = 0; i < board.length; i++) { twin[i] = board[i].clone(); } 

Now I get [[2, 0, 3], [4, 1, 5], [7, 8, 6]].

Other possibilities include declaring your new multidimensional array without cloning, and using loops and System.arraycopy to copy individual one-dimensional arrays.

Sign up to request clarification or add additional context in comments.

Comments

1

Quoting JLS Chapter 10. Arrays:

In the Java programming language, arrays are objects

No int[][] is not a primitive.


Quoting JLS 10.7. Array Members:

A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

The outer array is a new instance, the subarrays are not.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.