2

所以我在将 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])。

谁能解释这里发生了什么?

4

2 回答 2

4

问题出在这里:

myTable.myRows.add(currentRow);

您在ArrayList currentRow此处添加到“主”列表。请注意,在 Java 语义下,您正在添加对变量的引用。currentRow

在下一行,您立即清除currentRow

currentRow.clear()

因此,当您稍后尝试使用它时,“主”列表会从之前查找该引用并发现虽然有一个ArrayList对象,但其中不包含Strings。

你真正想做的是从一个 ArrayList的开始,所以用这个替换上一行:

currentRow = new ArrayList<String>();

然后旧对象仍然被“主”列表引用(因此它不会被垃圾收集),并且当以后访问它时,它的内容不会被清除。

于 2013-04-03T01:08:40.560 回答
1

不要清除当前行,而是在外循环内为每一行创建一个全新的 ArrayList。

当您将 currentRow 添加到列表时,您添加的是对列表的引用,而不是将继续独立存在的副本。

于 2013-04-03T01:08:33.400 回答