简体   繁体   中英

Why can't I access elements of 2D ArrayList?

I have a two dimensional ArrayList that is being populated with string values in a while loop. The values come from a CSV file that is read using BufferedReader and then put into a one dimensional ArrayList using StringTokenizer . The 1D ArrayList is added to the 2D ArrayList in a while loop.

My problem is that I cannot access the elements of the 2D array outside of the while loop. As you can see from the following code:

public String[][] readInCSV(String mg) {


    List<List<String>> twoDim = new ArrayList<List<String>>();
    List<String> row = new ArrayList<String>();
    try {

        BufferedReader CSVFile = new BufferedReader(new FileReader("C:\\minuteTest.csv"));
        String dataRow="";
        int y=0;

        while ((dataRow = CSVFile.readLine()) != null) {
            StringTokenizer st = new StringTokenizer(dataRow, ",");


            while(st.hasMoreTokens()){

                row.add(st.nextToken());

            }
            System.out.println("row: " + row.get(2));
            twoDim.add(row);
            System.out.println("twoDimTest: " + twoDim.get(y).get(2) + "  y: " + y);
            row.clear();
            y++;
        }

        for(int x=0; x<twoDim.size(); x++){

            System.out.println("twoDim: " + twoDim.get(x).size());
        }
        CSVFile.close();

    } 
    catch (FileNotFoundException e1) {
        System.out.println("file not found: " + e1.getMessage());
    } 
    catch (IOException e1) {
        System.out.println("could not read file: " + e1.getMessage());
    }


    return strArray;
}

"twoDimTest" prints out exactly what "row" does in the while loop, but "twoDim" prints out 0 in the for loop. If I try:

twoDim.get(0).get(2);

it returns an IndexOutOfBoundsExeception. If I try:

twoDim.size();

it returns the correct number of rows.

Why are the rows of my 2D array populated in the while loop, but not outside the while loop?
How can I access my 2D array outside of the while loop?

Your outer list contains many many copies of the same inner list, which you row.clear(); afterwards.

You need to create a new ArrayList<>() for each row, and not clear it.

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