【问题标题】:ArrayList.clear() in a two dimensional ArrayList(ArrayList of ArrayLists)ArrayList.clear() 中的二维 ArrayList(ArrayList of ArrayLists)
【发布时间】:2013-03-24 12:24:43
【问题描述】:

所以我在将 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 中)时,每次迭代时,我都会得到该行 PLUS其他行。

但是当我在将currentRow 添加到我的arrayList&lt;ArrayList&lt;String&gt; 之后调用currentRow.clear() 时,它实际上会清除我添加到主arrayList 以及currentRow 对象的数据...。我只想要currentRow ArrayList 为空,但不是我刚刚添加到 ArrayList 中的 ArrayList (Mytable.MyRows[currentRow])。

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

【问题讨论】:

    标签: java multidimensional-array arraylist


    【解决方案1】:

    问题出在这里:

    myTable.myRows.add(currentRow);

    您将ArrayList currentRow 添加到此处的“主”列表中。请注意,在 Java 语义下,您将 reference 添加到 currentRow 变量。

    在下一行,你立即清除currentRow

    currentRow.clear()

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

    您真正想要做的是从 new ArrayList 重新开始,因此将前一行替换为:

    currentRow = new ArrayList&lt;String&gt;();

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

    【讨论】:

    • 明白了,我认为这与引用有关,我的 java 很生锈。
    【解决方案2】:

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

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

    【讨论】:

    • 所以当我运行 currentRow.clear() 时,它也会清除存储在主列表中的引用,而不是仅仅清除 currentRow 的内容?
    猜你喜欢
    • 2018-02-28
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    • 2016-03-02
    相关资源
    最近更新 更多