List is overriding previously added record when a new record is inserted

Viewed 70

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]]
3 Answers

A common mistake. Move the construction of pairs_current into the inner if statement...

                if(j*k == sum-(j+k)){
                    //System.out.println("j:"+j+" k:"+k);
                    long[] pairs_current = new long[2];
                    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()));
                }

You are creating the long array at the top of the method, so there is only ever one array. You re-add the same array to the list and then change the values within it on the next loop. So the list has multiple entries but they all point to the same array.

As a rule its best to construct objects within the scope of where you are going to use them.

first let us take a look at your code

  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()));
            }

you have created an array of size 2 and filled it with 15,21and added it to the list when if statement runs for the first time and again when the if statement runs for the second time it added the new data that is 21,15 to the array and then added the array to the list but you forget that you have only one array and when the if statement runs for the second time it updates both the array with the same data that is 21,15

now the new if statement

       if(j*k == sum-(j+k)){
                //System.out.println("j:"+j+" k:"+k);
                long[] pairs_current = new long[2];
                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()));
            }

here every time the the if statement execute we are making a new array and adding it to the list, that is how you can get the desired output

First you are inserting array in list so the reference of that array is getting stored in list. Now on second time of loop again you are modifying the same array which get modified the first array added in list due to same reference. You can resolve this isue by using clone().

Replace list_all.add(pairs_current) with list_all.add(pairs_current.clone())

This is what I found the solution, there might better solution exists. It will be appreciated if any one can suggest other better solution.

Related