title: Why can't I access elements of 2D ArrayList?
body: <p>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 <code>BufferedReader</code> and then put into a one dimensional ArrayList using <code>StringTokenizer</code>.  The 1D ArrayList is added to the 2D ArrayList in a while loop.</p>
  
  <p>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:</p>
  
  <pre><code>public String[][] readInCSV(String mg) {
  
  
      List&lt;List&lt;String&gt;&gt; twoDim = new ArrayList&lt;List&lt;String&gt;&gt;();
      List&lt;String&gt; row = new ArrayList&lt;String&gt;();
      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&lt;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;
  }
  </code></pre>
  
  <p>"twoDimTest" prints out exactly what "row" does in the while loop, but "twoDim" prints out 0 in the for loop.  If I try:</p>
  
  <pre><code>twoDim.get(0).get(2);
  </code></pre>
  
  <p>it returns an IndexOutOfBoundsExeception.  If I try:</p>
  
  <pre><code>twoDim.size();
  </code></pre>
  
  <p>it returns the correct number of rows.</p>
  
  <p>Why are the rows of my 2D array populated in the while loop, but not outside the while loop? <br> How can I access my 2D array outside of the while loop?</p>