Skip to content

Commit

Permalink
Make UnmodifiableMultiset.removeIf(Predicate) unsupported
Browse files Browse the repository at this point in the history
Even if there's nothing to remove, `removeIf(Predicate)` should throw an
`UnsupportedOperationException`. This is theoretically an incompatible change, in that some existing code might have been calling `removeIf` with a predicate that is never true. None of Google's internal uses show this problem in tests.

Fixes #6702.
Closes #6703.

RELNOTES=`Multisets.unmodifiableMultiset(set).removeIf(predicate)` now throws an exception always, even if nothing matches `predicate`.
PiperOrigin-RevId: 564750701
  • Loading branch information
etellman authored and Google Java Core Libraries committed Sep 12, 2023
1 parent a770aea commit 61dbccf
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import java.util.Collections;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Predicate;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
Expand Down Expand Up @@ -64,6 +65,10 @@ public final boolean removeAll(Collection<?> oldElements) {
throw new UnsupportedOperationException();
}

public final boolean removeIf(Predicate<? super E> predicate) {
throw new UnsupportedOperationException();
}

public final boolean retainAll(Collection<?> elementsToKeep) {
throw new UnsupportedOperationException();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,11 @@ public static <E> void assertMultisetIsUnmodifiable(Multiset<E> multiset, E samp
}
assertCollectionsAreEquivalent(multiset, copy);

try {
multiset.removeIf(x -> false);
fail("removeIf(Predicate) succeeded on unmodifiable collection");
} catch (UnsupportedOperationException expected) {
}
assertCollectionsAreEquivalent(multiset, copy);

assertSetIsUnmodifiable(multiset.elementSet(), sampleElement);
Expand Down
5 changes: 5 additions & 0 deletions guava/src/com/google/common/collect/Multisets.java
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,11 @@ public boolean removeAll(Collection<?> elementsToRemove) {
throw new UnsupportedOperationException();
}

@Override
public boolean removeIf(java.util.function.Predicate<? super E> filter) {
throw new UnsupportedOperationException();
}

@Override
public boolean retainAll(Collection<?> elementsToRetain) {
throw new UnsupportedOperationException();
Expand Down

0 comments on commit 61dbccf

Please sign in to comment.