# Replace removeAll() with clear()

# Properties

Property Value
Rule ID CollectionRemoveAll
First seen in jSparrow version 1.0.0
Minimum Java version 1.2
Remediation cost 2 min
Links FindBugs

# Description

Simplifies the code by replacing all occurrences of removeAll() which have the current collection as parameter with clear(). Calling c.removeAll(c) to clear a collection is less clear, susceptible to errors from typos, less efficient and for some collections, might throw a ConcurrentModificationException.

# Benefits

Calling clear() instead of removeAll() makes code more clear and efficient, when at the same time less error prone.

# Code Changes

Pre

public String testIfCollectionIsEmpty(String input){
    List<String> resultList = generateList(input);

    resultList.removeAll(resultList);

    StringBuilder sb = new StringBuilder();

    resultList.stream().forEach((s)->sb.append(s));

    return sb.toString();
}

Post

public String testIfCollectionIsEmpty(String input){
    List<String> resultList = generateList(input);

    resultList.clear();

    StringBuilder sb = new StringBuilder();

    resultList.stream().forEach((s)->sb.append(s));

    return sb.toString();
}

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow version:

# Tags

1
default
You & jSparrow
default

Hey there! May I help you? 😊