Skip to content

Commit

Permalink
Check isEmpty() instead of size == 0.
Browse files Browse the repository at this point in the history
That way is simpler.

It's also somewhat better for users who pass a filtered collection, **but:**
- We may undo this change in the future (as we are considering approaches that would actually use the result of `size` for more than an emptiness check).
- A nonempty filtered collection will still apply the filter at least once during the `isEmpty` call, so that can still cause trouble if the filter has side effects or "call the filter until it returns `true`" is slow enough to matter.
- Other methods in Guava likely still trigger similar behavior when given a filtered collection, as do methods outside of Guava.

Fixes #7143 (for now)

RELNOTES=n/a
PiperOrigin-RevId: 623232817
  • Loading branch information
cpovirk authored and Google Java Core Libraries committed Apr 9, 2024
1 parent 48b6643 commit 911661a
Showing 1 changed file with 1 addition and 2 deletions.
3 changes: 1 addition & 2 deletions guava/src/com/google/common/collect/ImmutableSet.java
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,7 @@ public static <E> ImmutableSet<E> copyOf(Collection<? extends E> elements) {
return copyOfEnumSet((EnumSet<?>) elements);
}

int size = elements.size();
if (size == 0) {
if (elements.isEmpty()) {
// We avoid allocating anything.
return of();
}
Expand Down

0 comments on commit 911661a

Please sign in to comment.