What is the difference between ArrayList.clear() and ArrayList.removeAll()?

前端 未结 9 1851
不思量自难忘°
不思量自难忘° 2020-11-30 16:05

Assuming that arraylist is defined as ArrayList arraylist, is arraylist.removeAll(arraylist) equivalent to arraylist.clear()?

9条回答
  •  隐瞒了意图╮
    2020-11-30 16:45

    The source code for clear():

    public void clear() {
        modCount++;
    
        // Let gc do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;
    
        size = 0;
    }
    

    The source code for removeAll()(As defined in AbstractCollection):

    public boolean removeAll(Collection c) {
        boolean modified = false;
        Iterator e = iterator();
        while (e.hasNext()) {
            if (c.contains(e.next())) {
                e.remove();
                modified = true;
            }
        }
        return modified;
    }
    

    clear() is much faster since it doesn't have to deal with all those extra method calls.

    And as Atrey points out, c.contains(..) increases the time complexity of removeAll to O(n2) as opposed to clear's O(n).

提交回复
热议问题