java - 二维ArrayList中的ArrayList.clear()(ArrayList of ArrayLists)

标签 java multidimensional-array arraylist

因此,我在将 ArrayList 添加到 ArrayList 时遇到了一些问题。将其视为一张 table 。

这是一些示例代码:

 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 之后给我的arrayList<ArrayList<String> ,它实际上清除了我添加到主 arrayList 以及 currentRow 对象中的数据......并且我只想将 currentRow ArrayList 清空,而不是我刚刚添加到 ArrayList 中的 ArrayList (Mytable.MyRows[currentRow]) .

谁能解释一下这是怎么回事?

最佳答案

问题出在这里:

myTable.myRows.add(currentRow);

您添加ArrayList currentRow到这里的“主”列表。请注意,在 Java 语义下,您将引用添加到 currentRow变量。

在下一行,您立即清除 currentRow :

currentRow.clear()

因此,当您稍后尝试使用它时,“主”列表会查找之前的引用并发现虽然有 ArrayList对象,它不包含 String就在其中。

你真正想做的是从一个新的开始 ArrayList ,因此将前一行替换为:

currentRow = new ArrayList<String>();

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

关于java - 二维ArrayList中的ArrayList.clear()(ArrayList of ArrayLists),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15777152/

相关文章:

java - 为什么 UtteranceProgress Listener 不会在 Text to Speech 上被调用?

java - 如何在 Jackcess 中导入特定编码的文件?

c - 如何使用 [rows][cols] 索引打印出我正在访问的 int* ?

php - JSON 中的嵌套数组

java - JFrame 的边框布局定位不符合预期

Excel VBA - 多维数组进入非连续范围(使用单元格联合制作)

java - 从包含特定子字符串的 arraylist 元素中删除特定字符串

android parcelable字符串数组

java - 方法/构造函数中的 ArrayList - Java

Java:startingPath 为 "public static final"异常