简体   繁体   English

如何清除Java中的ArrayList?

[英]How to clear a ArrayList in Java?

The following iterate over an ArrayList : 以下遍历ArrayList

for (String[] line : dataList) {
//adding items in the list here
    item.add(line[0]);

  if(dataList.isEmpty()){ //attempting to clear dataList when it has iterated through to the last element but not working as expected
    dataList.clear()
   }
}

How can I clear the elements in the ArrayList after I have iterater over its elements? 对元素进行迭代后,如何清除ArrayList的元素?

Remove the if(dataList.isEmpty()) block and clear the list after the loop. 删除if(dataList.isEmpty())块,并在循环后清除列表。 Iterating does not remove items. 迭代不会删除项目。

The desired code is: 所需的代码是:

for (String[] line : dataList) {
    item.add(line[0]);
}
dataList.clear();

It should be something like, 应该是这样的

for (String[] line : dataList) {
    item.add(line[0]);
}

dataList.clear();

As others point out: 正如其他人指出的那样:

for (String[] line : dataList) {
    item.add(line[0]);
}
dataList.clear();

Will clear the list. 将清除列表。 If it's already empty, that's fine. 如果已经是空的,那很好。 clear() will do nothing and return normally. clear()将不执行任何操作并正常返回。

I've popped an answer in because you might wonder if you need to clear it at all. 我之所以弹出一个答案,是因为您可能想知道是否需要清除它。 If dataList goes out of scope at the end of the method then the garbage collector will clear up for you. 如果dataList在方法末尾超出范围,则垃圾收集器将为您清除。

If you're 'reusing' datalist in subsequent code then the best answer is - don't. 如果您要在后续代码中“重用” datalist ,那么最好的答案是-不。 Declare a local variable at the start of the loop. 在循环开始时声明一个局部变量。 It's certainly cleaner and often faster to just keep creating new objects rather than recycling. 当然,继续创建新对象而不是进行回收会更清洁,而且通常更快。

NB: There could be circumstances where clearing the list is appropriate. 注意:在某些情况下,清除列表是适当的。 If it's a class field that will continue beyond the method. 如果它是一个类字段,它将继续超出该方法。 However if it is the use as a temporary store seems inappropriate. 但是,如果将其用作临时存储似乎不合适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM