I've a Java code, In which there is a List which basically stores the long[] array. In a for loop the long[] array gets updated each time (if some condition satisfies) and it is added to the List. When a new array is added to List, the previously added array content is getting modified. How can I get the List with exact content what I added to it? Appreciate your suggestions. Thanks!
My Code: [can be executed]
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
removNb(26);
}
public static List<long[]> removNb(long n) {
if(n<1100){
long sum = 0;
long[] pairs_current = new long[2];
List<long[]> list_all = new ArrayList<>();
for (long i=1; i<=n; i++){
sum+= i;
}
for (long j=1; j<=n;j++){
for (long k=1; k<=n;k++){
if(j*k == sum-(j+k)){
//System.out.println("j:"+j+" k:"+k);
pairs_current[0] = j;
pairs_current[1] = k;
list_all.add(pairs_current);
System.out.println("pairs_current:"+Arrays.toString(pairs_current));
System.out.println("list_all:"+Arrays.deepToString(list_all.toArray()));
}
}
}
return list_all;
}
else {
return null;
}
}
}
Below is the expected output:
pairs_current:[15, 21]
list_all:[[15, 21]]
pairs_current:[21, 15]
list_all:[[15, 21], [21, 15]]
But I am getting below as response (you can see the first record also get modified):
pairs_current:[15, 21]
list_all:[[15, 21]]
pairs_current:[21, 15]
list_all:[[21, 15], [21, 15]]