0

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

        }


    }
}

1 Answer 1

2

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<>();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.