Java Collection isEmpty() and size() usage
In Java, both isEmpty()
and size()
are methods of the Collection
interface and are used to check if a collection has any elements. However, they work differently and may have performance implications depending on the collection implementation.
isEmpty()
:
- This method checks if a collection has no elements.
- It is generally more efficient than
size()
for this purpose because it often only needs to check an internal counter or a boolean flag rather than count elements. - Returns
true
if the collection contains no elements, otherwisefalse
.
if (collection.isEmpty()) {
// write your code when collection has no elements
}
size()
:
- This method returns the actual number of elements in the collection.
- It can sometimes be less efficient than
isEmpty()
if the collection needs to count elements (for example, in a linked list where traversal might be required). - Returns an integer representing the number of elements in the collection.
if (collection.size() == 0) {
// Write your code when collection has no elements
}
Which to Use?
Use
isEmpty()
when you only need to know if a collection has elements or not. It’s clearer and can be more efficient.Use
size()
if you need the actual count of elements, or if you’re performing operations based on the size.