Ritesh95
Ritesh95

Reputation: 57

Adding new elements to List replaces the previous elements

Getting wrong output Here I have 3 List "chkptPrice","fuelNeeded" and "motherList". So in a loop I add new elements to "chkptPrice" and "fuelNeeded", then after that I add both the list to the "motherList". When the Loop run for the first time, everything goes fine but after that when I add new elements using "chkptPrice" and "fuelNeeded" to "motherList", the whole List is replaced by same elements and the elements are repeated.

System.out.println("Enter the test cases");
    int tess = scan.nextInt();
    scan.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
    System.out.println("Enter the number of checkpoints: ");
    int checkpt = scan.nextInt();
    scan.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
    List<List<Integer>> motherList = new ArrayList<List<Integer>>();
    List<Integer> chkptPrice = new ArrayList<Integer>();
    List<Integer> fuelNeeded = new ArrayList<Integer>();

    for(int i=0; i<tess; i++)
    {
        chkptPrice.clear();
        fuelNeeded.clear();
        String[] price = scan.nextLine().split(" ");
        for(int j=0; j<checkpt; j++)
        {
            int intPrice = Integer.parseInt(price[j]);
            chkptPrice.add(intPrice);
        }
        String[] fueldist = scan.nextLine().split(" ");
        for(int j=0; j<checkpt; j++)
        {
            int intDist = Integer.parseInt(fueldist[j]);
            fuelNeeded.add(intDist);
        }
        System.out.println("Elements in chktPrice: "+chkptPrice);
        System.out.println("Elements in fuelNeeded: "+fuelNeeded);

        motherList.add(chkptPrice);
        motherList.add(fuelNeeded);



        System.out.println("Elements of motherList: "+motherList);
    }

===== Input ======

    2
    2
    1 3
    4 6
    4 9
    1 8

===== Output ======

{1st Loop}

    Elements in chktPrice: [1, 3]
    Elements in fuelNeeded: [4, 6]
    Elements of motherList: [[1, 3], [4, 6]]

{2nd Loop}

    Elements in chktPrice: [4, 9]
    Elements in fuelNeeded: [1, 8]
    Elements of motherList: [[4, 9], [1, 8], [4, 9], [1, 8]]

motherList elements should be

[[1, 3], [4, 6], [4, 9], [1, 8]]

Upvotes: 0

Views: 412

Answers (1)

user10367961
user10367961

Reputation:

When you invoke clear you are not creating a new list but removing the contents of an already existing list (you empty the contents of the lists already added in the previous iterations).

Then, when you add them again to the motherList in the current iteration, you just add two new references pointing to the same old objects (so you end up with 4 references pointing to two objects).

To fix this, you would have to reinitialize the lists instead of using clear.

chkptPrice.clear(); -> chkptPrice = new LinkedList<>(); 
fuelNeeded.clear(); -> fuelNeeded = new LinkedList<>(); 

Upvotes: 3

Related Questions