The Java Collections Framework provides two related methods for all Collection
objects:
size()
returns the number of entries in a Collection
, andisEmpty()
method returns true if (and only if) the Collection
is empty.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:
java.util.LinkedList
) might need to traverse the list to count the elements.ConcurrentHashMap
class needs to sum the entries in all of the map's "segments".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.