gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:25:19 31 4
gpt4 key购买 nike

所以我在将 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 (Mytable.MyRows[currentRow]) 的 ArrayList .

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

最佳答案

问题出在这里:

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/

31 4 0