简体   繁体   中英

Save data in ArrayList of ArrayList

I want to save data in a list that's the instance of another list. like a 2D ArrayList But, data is not being read properly

here is the code of constructor

ArrayList<ArrayList<Integer>> Planets;
Planets = new ArrayList<ArrayList<Integer>>();

here is the function that is reading data from file

public boolean readFile(String str){
    try(BufferedReader br = new BufferedReader(new FileReader(str))) {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();
        ArrayList temp = new ArrayList<Integer>();
        while (line != null) {
            temp.addAll(Arrays.asList(line.split(" ")));
            temp = getIntegerArray(temp);

            Planets.add(temp);
            temp.clear();

            line = br.readLine();
        }
        System.out.println(Planets);
    }
    catch(Exception e){
        return false;
    }
    return true;
}

Here is the content of file "input.txt"

1 0 0 0 0 0 0 0 1 0
1 1 1 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0

Generated output for System.out.println(Planets); is

[[1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], []]

But it should be

[[1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

I dont know where is the problem. Anyone who know, Please help me.

Try this..

Do that initilize ArrayList temp = new ArrayList<Integer>(); inside while loop and remove temp.clear(); like below

    StringBuilder sb = new StringBuilder();
    String line = br.readLine();
    while (line != null) {
        ArrayList temp = new ArrayList<Integer>();
        temp.addAll(Arrays.asList(line.split(" ")));
        temp = getIntegerArray(temp);

        Planets.add(temp);

        line = br.readLine();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM