Home > Blockchain >  Trying to update nested ArrayList within a for loop
Trying to update nested ArrayList within a for loop

Time:12-05

I am new to java and while trying to solve a prompt I ran into an issue which I couldn't find an answer to possibly due to my lack of understanding of the nature of the problem. I have an ArrayList consisting of integers nested within another ArrayList. I can update my temporary list outside of the loop in the very same manner but not within the loop. When I print mainList I receive an empty ArrayList within mainList for every integer input.

import java.util.*;

public class Lock {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        ArrayList<ArrayList<Integer>> mainList = new ArrayList<>();
        ArrayList<Integer> tempList = new ArrayList<>();



        while(input.hasNextInt()) {

            for (int i = 0; i < 4; i  ) {
                int n = input.nextInt();
                tempList.add(n);

            }
            mainList.add(tempList);
            tempList.clear();

        }
        System.out.println(mainList);

        input.close();

        int angleSum;


        for (ArrayList<Integer> integers : mainList) {

            //2 clockwise turns
            angleSum = 0;
            angleSum = angleSum   720;

            //init values within nested <Int> ArrayLists
            int val1 = integers.get(0);
            int val2 = integers.get(1);
            int val3 = integers.get(2);
            int val4 = integers.get(3);

            //Continue until first number in Combination

            angleSum = angleSum   (9 * Math.abs(val1 - val2));



            //CounterClockwise turn
            angleSum = angleSum   360;

            //Counter Clockwise until val3

            angleSum = angleSum   (360 - (9 * (39 - Math.abs(val2 - val3))));


            //Clockwise until val4
            angleSum = angleSum   (9 * Math.abs(val3 - val4));

            System.out.println(angleSum);

        }


    }
}

CodePudding user response:

When you call clear() on tempList, you remove the contents on the instance of the list that you have just added to the mainList.

You have to create new instance instead so that existing items in mainList are not affected:

// tempList.clear();  //! wrong
   tempList = new ArrayList<>();
  • Related