0

I am trying to put an arraylist of integers inside an arraylist of arraylist of integers . i tried.

public class test3{
    public static void main(String[] args) throws IOException{
        String text= null;
        ArrayList<ArrayList<Integer>> outerlist = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> innerlist = new ArrayList<>();

        int dept= 17;
        int arrv= 6;
        int[] arr = new int[1000];
        String[] stations = null;    
        FileReader file = new FileReader("test2.txt");
        BufferedReader br = new BufferedReader(file);
        while((text = br.readLine()) != null){
            innerlist.clear();
            stations = text.split(" ");
            //int[] array = Arrays.stream(stations).mapToInt(Integer::parseInt).toArray();

            for(int i = 0 ; i<stations.length ; i++){
                arr[i] = Integer.parseInt(stations[i]);
            }
            for(int j = 0 ; j<stations.length ; j++){
                innerlist.add(arr[j]);
            }
            outerlist.add(innerlist);

        }
        System.out.println(outerlist);
    }
}

it should output [[1, 17, 3, 150, 22], [2, 6, 34, 118], [5, 22, 3, 19, 6, 118, 250, 7], [10, 15, 89, 14, 33, 77, 2, 101, 50, 44]]

but instead it output: [[10, 15, 89, 14, 33, 77, 2, 101, 50, 44], [10, 15, 89, 14, 33, 77, 2, 101, 50, 44], [10, 15, 89, 14, 33, 77, 2, 101, 50, 44], [10, 15, 89, 14, 33, 77, 2, 101, 50, 44]]

the test file i am reading from (test2.txt) contains:

1 17 3 150 22

2 6 34 118

5 22 3 19 6 118 250 7

10 15 89 14 33 77 2 101 50 44

1 Answer 1

2

Just change innerlist.clear() to innerlist = new ArrayList<>();.

When you add inner list to outer list, it's add by memory address, so, when you change inner list, it changes in all the place. But when you do innerlist = new ArrayList<>(); you creates new list, and memory adderss was changed, but it's data isn't changed

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.