所以我在将 ArrayLists 添加到我的 ArrayList 时遇到了一些问题。把它想象成一张桌子。
这是一些示例代码:
ArrayList<String> currentRow = new ArrayList<String>();
while ((myLine = myBuffered.readLine()) != null) {
if(rowCount == 0) {// get Column names since it's the first row
String[] mySplits;
mySplits = myLine.split(","); //split the first row
for(int i = 0;i<mySplits.length;++i){ //add each element of the splits array to the myColumns ArrayList
myTable.myColumns.add(mySplits[i]);
myTable.numColumns++;
}
}
else{ //rowCount is not zero, so this is data, not column names.
String[] mySplits = myLine.split(","); //split the line
for(int i = 0; i<mySplits.length;++i){
currentRow.add(mySplits[i]); //add each element to the row Arraylist
}
myTable.myRows.add(currentRow);//add the row arrayList to the myRows ArrayList
currentRow.clear(); //clear the row since it's already added
//the problem lies here *****************
}
rowCount++;//increment rowCount
}
}
问题是当我不调用currentRow.clear()
来清除我在每次迭代中使用的 ArrayList 的内容(放入我的 ArrayList 的 ArrayList 中)时,每次迭代,我都会得到该行加上每隔一行。
但是,当我currentRow.clear()
在添加currentRow
到 my之后调用时arrayList<ArrayList<String>
,它实际上会清除我添加到主 arrayList 以及 currentRow 对象的数据....而且我只希望 currentRow ArrayList 为空,而不是我刚刚添加到的 ArrayList我的 ArrayList (Mytable.MyRows[currentRow])。
谁能解释这里发生了什么?