user2683631 user2683631 - 1 month ago 20
Java Question

un-synchronize an array from arraylist

For a basic example

int[] B;
B=new int[4];
B[0]=4;
B[1]=3;
B[2]=2;
B[3]=1;
ArrayList<int[]> C = new ArrayList<int[]>();
C.add(B);
B[0]=3;
B[1]=2;
B[2]=4;
B[3]=1;
C.add(B);


I have a basic array that I added to the list, I am changing the array B values as I go along in a loop which I wanted to add each new B from a loop to C but C is syncing with B automatically which prevent me from adding a new B. The reason I need a new B to be added is for tracking the progress of the loop and prevent duplication.

Currently C is always size of 1 with the new B.

Answer

Save a copy of the array instead:

C.add(Arrays.copyOf(B)); //or System#arraycopy

Java is pass by value of reference, an array is therefore pass by reference, and won't copy itself.

You should try to adhere to a common style guide (like Oracle/Google variable naming conventions).