Web / Apache Commons Collections Interview questions
Why is CollectionUtils.isEmpty() preferred over calling isEmpty() directly?
Calling collection.isEmpty() directly assumes the reference itself is non-null; if collection is null - which happens often with optional fields, method parameters, or values pulled from external data sources - that call throws a NullPointerException before the emptiness check even runs.
// fragile: NPE if items is null if (!items.isEmpty()) { ... } // null-safe if (CollectionUtils.isNotEmpty(items)) { ... }
CollectionUtils.isEmpty(coll) and isNotEmpty(coll) fold the null-check and the emptiness check into one call, so the same guard condition (coll == null || coll.isEmpty()) doesn't need to be rewritten at every call-site.
Beyond just avoiding NPEs, it also improves readability: a reader instantly recognizes the null-safe intent from the method name, rather than having to infer it from a compound boolean expression each time.
More Related questions...