[英]Why can't I access elements of 2D ArrayList?
我有一個二維的ArrayList在while循環中填充了字符串值。 這些值來自使用BufferedReader
讀取的CSV文件,然后使用StringTokenizer
將其放入一維ArrayList中。 1D ArrayList在while循環中添加到2D ArrayList中。
我的問題是我無法在while循環之外訪問2D數組的元素。 從以下代碼中可以看到:
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”精確地打印出while循環中“行”的功能,但是“ twoDim”卻在for循環中打印出0。 如果我嘗試:
twoDim.get(0).get(2);
它返回一個IndexOutOfBoundsExeception。 如果我嘗試:
twoDim.size();
它返回正確的行數。
為什么2D數組的行填充在while循環中,而不是在while循環外?
如何在while循環之外訪問2D數組?
您的外部列表包含同一內部列表的許多副本,您可以在row.clear();
然后。
您需要為每一行創建一個new ArrayList<>()
,而不清除它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.