为什么我会使用list.clear()

Jav*_*per 3 java collections garbage-collection

java中的Arraylist有一个方法调用clear().为什么我会选择使用明确的辞职参考?

list.clear()
Run Code Online (Sandbox Code Playgroud)

VS

list = new ArrayList() ? 
Run Code Online (Sandbox Code Playgroud)

看起来list.clear()会慢一点,在第二种情况下,GC会处理清理并让我们的生活更轻松吗?

das*_*ght 9

list.clear()其他一些代码引用同一个列表时,您将使用它.

例如,如果您遇到这种情况,则重新分配不起作用:

class Watcher {
    private final List<String> list;
    public Watcher(List<String> l) { list = l; }
    public void doSomething() {
        // Use list
    }
}

void main() {
    List<String> lst = new ArrayList<String>();
    Watcher w = new Watcher(lst);
    ...
    // At this point lst.clear() is different from lst = new List<String>()
}
Run Code Online (Sandbox Code Playgroud)