Pitfall - Using size to test if a collection is empty is inefficient.suggest change
The Java Collections Framework provides two related methods for all
size()returns the number of entries in a
isEmpty()method returns true if (and only if) the
Both methods can be used to test for collection emptiness. For example:
Collection<String> strings = new ArrayList<>(); boolean isEmpty_wrong = strings.size() == 0; // Avoid this boolean isEmpty = strings.isEmpty(); // Best
While these approaches look the same, some collection implementations do not store the size. For such a collection, the implementation of
size() needs to calculate the size each time it is called. For instance:
- A simple linked list class (but not the
java.util.LinkedList) might need to traverse the list to count the elements.
ConcurrentHashMapclass needs to sum the entries in all of the map’s “segments”.
- A lazy implementation of a collection might need to realize the entire collection in memory in order to count the elements.
By contrast, an
isEmpty() method only needs to test if there is at least one element in the collection. This does not entail counting the elements.
size() == 0 is not always less efficient that
isEmpty(), it is inconceivable for a properly implemented
isEmpty() to be less efficient than
size() == 0. Hence
isEmpty() is preferred.