使用clear()和removeAll()清空ArrayList区别
学习如何在Java中清空一个ArrayList。清空一个列表意味着从列表中删除所有元素。这相当于将列表重置为没有存储任何元素的初始状态。
要清空Java中的ArrayList,我们可以使用两种方法。
- ArrayList.clear()
- ArrayList.removeAll()
这两种方法最终都会清空列表。但它们在执行清空操作的方式上有所不同。我们看下使用clear()和removeAll()清空ArrayList的区别。
1.使用clear()清空ArrayList
以下Java程序使用clear() API清空一个ArrayList。
ArrayList<String> list = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e")); list.clear(); Assertions.assertEquals(0, list.size());
2. 使用removeAll()清空ArrayList
使用removeAll()方法删除ArrayList的所有元素的Java程序。removeAll()方法会删除当前列表中在指定集合中存在的所有元素。
在这个例子中,我们将列表的自引用传递给removeAll()方法。
ArrayList<String> list = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e")); list.removeAll(list); Assertions.assertEquals(0, list.size());
3.clear()和removeAll()之间的区别
正如我之前所说,这两种方法都可以清空一个列表。但它们的不同之处在于它们如何清空列表。让我们看看这两种方法的代码,以了解它们执行的操作。
clear()方法很简单。它遍历列表并将每个索引分配为null。
public void clear() { // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; }
在removeAll()方法中,它首先使用contains()方法检查元素是否存在。如果元素存在,则将其从列表中删除。这对所有循环中的元素都有效。
public boolean removeAll(Collection<?> c) { Objects.requireNonNull(c); return batchRemove(c, false); } private boolean batchRemove(Collection<?> c, boolean complement) { final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try { for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; } finally { // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. if (r != size) { System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; } if (w != size) { // clear to let GC do its work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified; }
4.结论
通过查看这两种方法的源代码,我们可以安全地说,clear()方法的性能要好得多,因为它执行的语句数量较少。
由于对contains()方法的额外调用,removeAll()方法在性能上表现不佳。但是,在某些情况下,如合并两个ArrayList而不包含重复元素,removeAll()方法仍然很有用。