Pitfall - Using size to test if a collection is empty is inefficient.

suggest change

The Java Collections Framework provides two related methods for all Collection objects:

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:

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.

While 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.

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents