Java 二维ArrayList中的ArrayList.clear()(ArrayList中的ArrayList)
因此,我在向ArrayList添加ArrayList时遇到了一些问题。把这当作一张桌子 下面是一些示例代码:Java 二维ArrayList中的ArrayList.clear()(ArrayList中的ArrayList),java,multidimensional-array,arraylist,Java,Multidimensional Array,Arraylist,因此,我在向ArrayList添加ArrayList时遇到了一些问题。把这当作一张桌子 下面是一些示例代码: ArrayList<String> currentRow = new ArrayList<String>(); while ((myLine = myBuffered.readLine()) != null) { if(rowCount == 0) {// get Column names since it's the first row
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
}
}
ArrayList currentRow=new ArrayList();
而((myLine=myBuffered.readLine())!=null){
如果(rowCount==0){//获取列名,因为它是第一行
字符串[]mySplits;
mySplits=myLine.split(“,”;//拆分第一行
对于(int i=0;i不清除当前行,而是在外部循环内为每一行创建一个全新的ArrayList
将currentRow添加到列表时,您是在添加对列表的引用,而不是将继续独立存在的副本。问题在于:
myTable.myRows.add(currentRow);
您将ArrayList currentRow
添加到此处的“主”列表中。请注意,在Java语义下,您添加了对currentRow
变量的引用
在下一行中,立即清除currentRow
:
currentRow.clear()
因此,当您稍后尝试使用它时,“主”列表会从之前查找该引用,并发现虽然存在ArrayList
对象,但其中不包含字符串
您真正想做的是用一个新的ArrayList
重新开始,因此将前一行替换为以下内容:
currentRow=newArrayList();
然后旧对象仍然被“主”列表引用(因此它不会被垃圾收集),并且当以后访问它时,它的内容不会被清除。所以当我运行currentRow.clear()时它还清除了存储在主列表中的引用,而不仅仅是清除了currentRow的内容?明白了,我想这与引用有关,我的java已经生锈了。