简体   繁体   English

为什么我不能访问2D ArrayList的元素?

[英]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. 我有一个二维的ArrayList在while循环中填充了字符串值。 The values come from a CSV file that is read using BufferedReader and then put into a one dimensional ArrayList using StringTokenizer . 这些值来自使用BufferedReader读取的CSV文件,然后使用StringTokenizer将其放入一维ArrayList中。 The 1D ArrayList is added to the 2D ArrayList in a while loop. 1D ArrayList在while循环中添加到2D ArrayList中。

My problem is that I cannot access the elements of the 2D array outside of the while loop. 我的问题是我无法在while循环之外访问2D数组的元素。 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. “ twoDimTest”精确地打印出while循环中“行”的功能,但是“ twoDim”却在for循环中打印出0。 If I try: 如果我尝试:

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

it returns an IndexOutOfBoundsExeception. 它返回一个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? 为什么2D数组的行填充在while循环中,而不是在while循环外?
How can I access my 2D array outside of the while loop? 如何在while循环之外访问2D数组?

Your outer list contains many many copies of the same inner list, which you row.clear(); 您的外部列表包含同一内部列表的许多副本,您可以在row.clear(); afterwards. 然后。

You need to create a new ArrayList<>() for each row, and not clear it. 您需要为每一行创建一个new ArrayList<>() ,而不清除它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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