I have an two-dimensional array number2 . I set it equal to number2copy with number2copy = number2
Then, I call a method Zeroed passing it the 2d array ToBeZeroed. This method fills the array with 0s, and I know it works. It returns ToBeZeroed full of zeros. But, when I put number2 = ToBeZeroed;
number2copy is also filled with zeros. How can I break up these things so a change in one does not cause a change in the other? They are unrelated arrays, so they need to be handled separately
I have an two-dimensional array number2 . I set it equal to number2copy with
Share
Java is not C++. You’re copying the reference to the array attributed to the first dimension, not the array object and array sub-objects. You need to use
number2copy = (int[][])deepCopy(number2);, which will perform a deep array copy which is appropriate for your needs, including copies of second dimension arrays contained within. Substituteint[][]for the 2D array datatype used which you didn’t tell us about 🙂 Additionally, to check if one object is equal to another,==will check the reference to the first dimension array of a 2D array, which is probably not what you want. For deep checking, useArrays.deepEquals(number2, number2copy);, which should work fine.Deep copy source code:
See here for a short explanation.
Edit: I only just noticed that he said 2D array, so modified answer appropriately 🙂