1. Overview

In this quick tutorial, we’ll learn about two Collection methods that might seem to do the same thing, but aren’t: clear() and removeAll().

We’ll first see the method definitions and then use them in short examples.

2. Collection.clear()

We’ll first dive into the Collection.clear() method. Let’s check the Javadoc of the method. According to it, the purpose of clear() is to remove every single element from the list.

So, basically, calling clear() on any list will result in the list becoming empty.

3. Collection.removeAll()

We’ll now have a look at the Javadoc of Collection.removeAll(). We can see that the method takes a Collection as an argument. And its purpose is to remove all common elements between the list and the collection.

So, when calling it on a collection, it will remove all elements from the passed argument that are also in the collection on which we call removeAll().

4. Examples

Let’s now look at some code to see those methods in action. We’ll first create a test class with the name ClearVsRemoveAllUnitTest.

After that, we’ll create a first test for Collection.clear().

We’ll initialize a collection of Integers with a few numbers and call clear() on it so that no element remains in the list:

@Test
void whenClear_thenListBecomesEmpty() {
    Collection<Integer> collection = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

    collection.clear();

    assertTrue(collection.isEmpty());
}

As we can see the collection is empty after clear() being called.

Let’s create a second test with two collections, one with numbers from 1 to 5 and the other with numbers from 3 to 7. After that, we’ll call removeAll() on the first collection with the second one as a parameter.

We’ll expect only the numbers 1 and 2 to remain in the first collection (while the second one is unchanged):

@Test
void whenRemoveAll_thenFirstListMissElementsFromSecondList() {
    Collection<Integer> firstCollection = new ArrayList<>(
      Arrays.asList(1, 2, 3, 4, 5));
    Collection<Integer> secondCollection = new ArrayList<>(
      Arrays.asList(3, 4, 5, 6, 7));

    firstCollection.removeAll(secondCollection);

    assertEquals(
      Arrays.asList(1, 2), 
      firstCollection);
    assertEquals(
      Arrays.asList(3, 4, 5, 6, 7), 
      secondCollection);
}

And our expectations are met. Only the numbers 1 and 2 are remaining in the first collection and the second one hasn’t been changed.

5. Conclusion

In this article, we’ve seen the purposes of Collection.clear() and Collection.removeAll().

Despite what we might think at first, they aren’t doing the same thing. clear() deletes every element from the collection and removeAll() one only removes the elements matching those from another Collection.

And, as always, the code can be found over on GitHub.