Java Multiple Array Copy Question!

Asked 2 years ago, Updated 2 years ago, 41 views

While solving the problem yesterday, I wanted to copy the two-dimensional array A to the two-dimensional array B to System.arraycopy and change the content value of B only.

But changing the value of array B also changed the value of array A, which made it a little difficult. If you copy a two-dimensional array with System.arraycopy, it seems that array B refers to array A.

All I want to do is copy the values of the real array, not the references, so that they don't affect each other if the contents change inside. Is there a method in Java that influences each other and copies an array?

Or is it just a way to put the value one by one using a repeating sentence?

Finally, if there is a method, I want to know how much difference there is between the method and the repetition rate.

Please let me know if there is anything wrong with the above!

Attached is the source code!

int[][] test = new int[][] {{1,1},{2,2},{3,3}};
int[][] test2 = new int[3][2];
System.arraycopy(test, 0, test2, 0, 3);
test2[0][0]++;

If you do so, the value of test2 also affects the test.

I'd appreciate it if you could tell me the explanation and solution!

java array

2022-09-22 12:52

1 Answers

As I mentioned in the question below, The arraycopy method is a shallow copy method. It's just a copy of the reference. You must copy the internal array while touring the external array.

Please refer to the link below.

https://stackoverflow.com/questions/1564832/how-do-i-do-a-deep-copy-of-a-2d-array-in-java


2022-09-22 12:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.