java中的Arraylist有一个方法调用clear().为什么我会选择使用明确的辞职参考?
list.clear()
VS
list = new ArrayList() ?
看起来像list.clear()会慢一些,在第二种情况下,GC会处理清理并让我们的生活更轻松吗?
解决方法:
当其他一些代码引用同一个列表时,您将使用list.clear().
例如,如果您遇到这种情况,则重新分配不起作用:
class Watcher {
private final List list;
public Watcher(List l) { list = l; }
public void doSomething() {
// Use list
}
}
void main() {
List lst = new ArrayList();
Watcher w = new Watcher(lst);
...
// At this point lst.clear() is different from lst = new List()
}
标签:java,collections,garbage-collection
来源: https://codeday.me/bug/20190713/1454109.html