Skip to content

Commit a279b88

Browse files
Cindy KrafftGoogle Java Core Libraries
authored andcommitted
Make filtered NavigableMap views return snapshot entries from pollFirstEntry(), etc. (and similarly for ForwardingNavigableMap.standard*Entry).
And update `NavigableMapTestSuiteBuilder` to require immutable entries from those methods. For simplicity, I'll focus on the `NavigableMap` case in the description below: `Maps.filterKeys`, `filterValues` and `filterEntries` on a `NavigableMap` returned the backing map's live entries from their navigation methods. This caused two problems: ### Removing an `Entry` from the backing map might mutate the `Entry` `pollFirstEntry()` and `pollLastEntry()` removed the entry through the backing `entrySet` iterator and then returned that same entry object. When `TreeMap` removes a node with two children, it copies the successor's key and value into that node, so the returned entry could show a different mapping. For example: - `Maps.filterKeys(TreeMap{1=one, 2=two, 3=three}, k -> k != 1) .pollFirstEntry()` returned `3=three` instead of `2=two`. - Draining `filterKeys(TreeMap{0..9}, odd)` with `pollFirstEntry()` returned keys [2, 4, 6, 7, 9] instead of [1, 3, 5, 7, 9]. ### Navigation methods are supposed to return snapshots `firstEntry()`, `lastEntry()`, `ceilingEntry()`, `floorEntry()`, `higherEntry()` and `lowerEntry()` returned live entries whose `setValue` wrote through to the backing map. This is bad for two reasons: - [`NavigableMap`](https://docs.oracle.com/en/java/javase/27/docs/api/java.base/java/util/NavigableMap.html) specifies that these methods return snapshot entries that don't support `setValue`. - Even if they were to support `setValue`, maps that are filtered by value (or by the full entry contents) should check that the predicate allows the new value. --- Now, all these methods return snapshots. But we continue to override `entrySet()` in a way that allows its entries to support `setValue` (with the predicate check). Finally, I've moved `Iterables.removeFirstMatching` from `Iterables` to `Sets`. That is now the only location that it's used from, since it is no longer used from `Maps`. Along the way, I renamed it to "`pollFirstMatching`" to more closely match the methods that it's used from. Fixes #8692 I filed b/566253750 for a similar question in `SortedMultiset`. RELNOTES=n/a PiperOrigin-RevId: 988966779
1 parent 4d41665 commit a279b88

16 files changed

Lines changed: 604 additions & 112 deletions

File tree

‎android/guava-testlib/src/com/google/common/collect/testing/testers/NavigableMapNavigationTester.java‎

Lines changed: 30 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -115,49 +115,49 @@ public void testEmptyMapPollLast() {
115115

116116
@CollectionSize.Require(ONE)
117117
public void testSingletonMapFirst() {
118-
assertEquals(a, navigableMap.firstEntry());
118+
assertEqualImmutableEntry(a, navigableMap.firstEntry());
119119
}
120120

121121
@MapFeature.Require(SUPPORTS_REMOVE)
122122
@CollectionSize.Require(ONE)
123123
public void testSingletonMapPollFirst() {
124-
assertEquals(a, navigableMap.pollFirstEntry());
124+
assertEqualImmutableEntry(a, navigableMap.pollFirstEntry());
125125
assertTrue(navigableMap.isEmpty());
126126
}
127127

128128
@CollectionSize.Require(ONE)
129129
public void testSingletonMapNearby() {
130130
assertNull(navigableMap.lowerEntry(k0()));
131131
assertNull(navigableMap.lowerKey(k0()));
132-
assertEquals(a, navigableMap.floorEntry(k0()));
132+
assertEqualImmutableEntry(a, navigableMap.floorEntry(k0()));
133133
assertEquals(a.getKey(), navigableMap.floorKey(k0()));
134-
assertEquals(a, navigableMap.ceilingEntry(k0()));
134+
assertEqualImmutableEntry(a, navigableMap.ceilingEntry(k0()));
135135
assertEquals(a.getKey(), navigableMap.ceilingKey(k0()));
136136
assertNull(navigableMap.higherEntry(k0()));
137137
assertNull(navigableMap.higherKey(k0()));
138138
}
139139

140140
@CollectionSize.Require(ONE)
141141
public void testSingletonMapLast() {
142-
assertEquals(a, navigableMap.lastEntry());
142+
assertEqualImmutableEntry(a, navigableMap.lastEntry());
143143
}
144144

145145
@MapFeature.Require(SUPPORTS_REMOVE)
146146
@CollectionSize.Require(ONE)
147147
public void testSingletonMapPollLast() {
148-
assertEquals(a, navigableMap.pollLastEntry());
148+
assertEqualImmutableEntry(a, navigableMap.pollLastEntry());
149149
assertTrue(navigableMap.isEmpty());
150150
}
151151

152152
@CollectionSize.Require(SEVERAL)
153153
public void testFirst() {
154-
assertEquals(a, navigableMap.firstEntry());
154+
assertEqualImmutableEntry(a, navigableMap.firstEntry());
155155
}
156156

157157
@MapFeature.Require(SUPPORTS_REMOVE)
158158
@CollectionSize.Require(SEVERAL)
159159
public void testPollFirst() {
160-
assertEquals(a, navigableMap.pollFirstEntry());
160+
assertEqualImmutableEntry(a, navigableMap.pollFirstEntry());
161161
assertEquals(entries.subList(1, entries.size()), copyToList(navigableMap.entrySet()));
162162
}
163163

@@ -171,54 +171,54 @@ public void testLower() {
171171
resetWithHole();
172172
assertEquals(null, navigableMap.lowerEntry(a.getKey()));
173173
assertEquals(null, navigableMap.lowerKey(a.getKey()));
174-
assertEquals(a, navigableMap.lowerEntry(b.getKey()));
174+
assertEqualImmutableEntry(a, navigableMap.lowerEntry(b.getKey()));
175175
assertEquals(a.getKey(), navigableMap.lowerKey(b.getKey()));
176-
assertEquals(a, navigableMap.lowerEntry(c.getKey()));
176+
assertEqualImmutableEntry(a, navigableMap.lowerEntry(c.getKey()));
177177
assertEquals(a.getKey(), navigableMap.lowerKey(c.getKey()));
178178
}
179179

180180
@CollectionSize.Require(SEVERAL)
181181
public void testFloor() {
182182
resetWithHole();
183-
assertEquals(a, navigableMap.floorEntry(a.getKey()));
183+
assertEqualImmutableEntry(a, navigableMap.floorEntry(a.getKey()));
184184
assertEquals(a.getKey(), navigableMap.floorKey(a.getKey()));
185-
assertEquals(a, navigableMap.floorEntry(b.getKey()));
185+
assertEqualImmutableEntry(a, navigableMap.floorEntry(b.getKey()));
186186
assertEquals(a.getKey(), navigableMap.floorKey(b.getKey()));
187-
assertEquals(c, navigableMap.floorEntry(c.getKey()));
187+
assertEqualImmutableEntry(c, navigableMap.floorEntry(c.getKey()));
188188
assertEquals(c.getKey(), navigableMap.floorKey(c.getKey()));
189189
}
190190

191191
@CollectionSize.Require(SEVERAL)
192192
public void testCeiling() {
193193
resetWithHole();
194-
assertEquals(a, navigableMap.ceilingEntry(a.getKey()));
194+
assertEqualImmutableEntry(a, navigableMap.ceilingEntry(a.getKey()));
195195
assertEquals(a.getKey(), navigableMap.ceilingKey(a.getKey()));
196-
assertEquals(c, navigableMap.ceilingEntry(b.getKey()));
196+
assertEqualImmutableEntry(c, navigableMap.ceilingEntry(b.getKey()));
197197
assertEquals(c.getKey(), navigableMap.ceilingKey(b.getKey()));
198-
assertEquals(c, navigableMap.ceilingEntry(c.getKey()));
198+
assertEqualImmutableEntry(c, navigableMap.ceilingEntry(c.getKey()));
199199
assertEquals(c.getKey(), navigableMap.ceilingKey(c.getKey()));
200200
}
201201

202202
@CollectionSize.Require(SEVERAL)
203203
public void testHigher() {
204204
resetWithHole();
205-
assertEquals(c, navigableMap.higherEntry(a.getKey()));
205+
assertEqualImmutableEntry(c, navigableMap.higherEntry(a.getKey()));
206206
assertEquals(c.getKey(), navigableMap.higherKey(a.getKey()));
207-
assertEquals(c, navigableMap.higherEntry(b.getKey()));
207+
assertEqualImmutableEntry(c, navigableMap.higherEntry(b.getKey()));
208208
assertEquals(c.getKey(), navigableMap.higherKey(b.getKey()));
209209
assertEquals(null, navigableMap.higherEntry(c.getKey()));
210210
assertEquals(null, navigableMap.higherKey(c.getKey()));
211211
}
212212

213213
@CollectionSize.Require(SEVERAL)
214214
public void testLast() {
215-
assertEquals(c, navigableMap.lastEntry());
215+
assertEqualImmutableEntry(c, navigableMap.lastEntry());
216216
}
217217

218218
@MapFeature.Require(SUPPORTS_REMOVE)
219219
@CollectionSize.Require(SEVERAL)
220220
public void testPollLast() {
221-
assertEquals(c, navigableMap.pollLastEntry());
221+
assertEqualImmutableEntry(c, navigableMap.pollLastEntry());
222222
assertEquals(entries.subList(0, entries.size() - 1), copyToList(navigableMap.entrySet()));
223223
}
224224

@@ -254,4 +254,14 @@ public void testTailMapExclusive() {
254254
public void testTailMapInclusive() {
255255
assertTrue(navigableMap.tailMap(a.getKey(), true).containsKey(a.getKey()));
256256
}
257+
258+
private void assertEqualImmutableEntry(Entry<K, V> expected, Entry<K, V> actual) {
259+
assertEquals(expected, actual);
260+
261+
V currentValue = expected.getValue();
262+
assertThrows(UnsupportedOperationException.class, () -> actual.setValue(currentValue));
263+
264+
V otherValue = v3();
265+
assertThrows(UnsupportedOperationException.class, () -> actual.setValue(otherValue));
266+
}
257267
}

‎android/guava-tests/test/com/google/common/collect/ForwardingNavigableMapTest.java‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
import static com.google.common.collect.Maps.immutableEntry;
2020
import static com.google.common.truth.Truth.assertThat;
21+
import static org.junit.Assert.assertThrows;
2122

2223
import com.google.common.base.Function;
2324
import com.google.common.collect.testing.NavigableMapTestSuiteBuilder;
@@ -37,6 +38,7 @@
3738
import java.util.NavigableSet;
3839
import java.util.Set;
3940
import java.util.SortedMap;
41+
import java.util.TreeMap;
4042
import junit.framework.Test;
4143
import junit.framework.TestCase;
4244
import junit.framework.TestSuite;
@@ -298,6 +300,7 @@ public void testStandardLastEntry() {
298300
NavigableMap<String, Integer> forwarding =
299301
new StandardLastEntryForwardingNavigableMap<>(new SafeTreeMap<String, Integer>());
300302
assertThat(forwarding.lastEntry()).isNull();
303+
301304
forwarding.put("b", 2);
302305
assertEquals(immutableEntry("b", 2), forwarding.lastEntry());
303306
forwarding.put("c", 3);
@@ -306,6 +309,51 @@ public void testStandardLastEntry() {
306309
assertEquals(immutableEntry("c", 3), forwarding.lastEntry());
307310
forwarding.remove("c");
308311
assertEquals(immutableEntry("b", 2), forwarding.lastEntry());
312+
313+
Entry<String, Integer> entry = forwarding.lastEntry();
314+
assertThrows(UnsupportedOperationException.class, () -> entry.setValue(0));
315+
}
316+
317+
public void testStandardPollFirstEntry_twoChildren() {
318+
TreeMap<Integer, String> map = new TreeMap<>();
319+
map.put(1, "one");
320+
map.put(2, "two");
321+
map.put(3, "three");
322+
NavigableMap<Integer, String> forwarding =
323+
new ForwardingNavigableMap<Integer, String>() {
324+
@Override
325+
protected NavigableMap<Integer, String> delegate() {
326+
return map.tailMap(2, true);
327+
}
328+
329+
@Override
330+
public @Nullable Entry<Integer, String> pollFirstEntry() {
331+
return standardPollFirstEntry();
332+
}
333+
};
334+
assertThat(forwarding.pollFirstEntry()).isEqualTo(immutableEntry(2, "two"));
335+
}
336+
337+
public void testStandardPollLastEntry_twoChildren() {
338+
TreeMap<Integer, String> map = new TreeMap<>();
339+
map.put(1, "one");
340+
map.put(2, "two");
341+
map.put(3, "three");
342+
NavigableMap<Integer, String> forwarding =
343+
new ForwardingNavigableMap<Integer, String>() {
344+
@Override
345+
protected NavigableMap<Integer, String> delegate() {
346+
return map.headMap(2, true);
347+
}
348+
349+
@Override
350+
public @Nullable Entry<Integer, String> pollLastEntry() {
351+
return standardPollLastEntry();
352+
}
353+
};
354+
Entry<Integer, String> entry = forwarding.pollLastEntry();
355+
assertThat(entry).isEqualTo(immutableEntry(2, "two"));
356+
assertThrows(UnsupportedOperationException.class, () -> entry.setValue("modified"));
309357
}
310358

311359
@SuppressWarnings({"rawtypes", "unchecked"})

‎android/guava-tests/test/com/google/common/collect/MapsTest.java‎

Lines changed: 126 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616

1717
package com.google.common.collect;
1818

19+
import static com.google.common.collect.Maps.filterKeys;
20+
import static com.google.common.collect.Maps.filterValues;
1921
import static com.google.common.collect.Maps.immutableEntry;
2022
import static com.google.common.collect.Maps.newConcurrentMap;
2123
import static com.google.common.collect.Maps.newEnumMap;
@@ -50,6 +52,7 @@
5052
import java.io.IOException;
5153
import java.io.StringReader;
5254
import java.lang.reflect.Field;
55+
import java.util.ArrayList;
5356
import java.util.Arrays;
5457
import java.util.Collection;
5558
import java.util.Collections;
@@ -528,7 +531,7 @@ public void testMapDifferencePredicateTypical() {
528531
+ "value differences={3=(F, c), 5=(G, e)}");
529532
}
530533

531-
private static final SortedMap<Integer, Integer> SORTED_EMPTY = Maps.newTreeMap();
534+
private static final SortedMap<Integer, Integer> SORTED_EMPTY = new TreeMap<>();
532535
private static final ImmutableSortedMap<Integer, Integer> SORTED_SINGLETON =
533536
ImmutableSortedMap.of(1, 2);
534537

@@ -618,9 +621,9 @@ public void testSortedMapDifferenceTypical() {
618621

619622
public void testSortedMapDifferenceImmutable() {
620623
SortedMap<Integer, String> left =
621-
Maps.newTreeMap(ImmutableSortedMap.of(1, "a", 2, "b", 3, "c", 4, "d", 5, "e"));
624+
new TreeMap<>(ImmutableSortedMap.of(1, "a", 2, "b", 3, "c", 4, "d", 5, "e"));
622625
SortedMap<Integer, String> right =
623-
Maps.newTreeMap(ImmutableSortedMap.of(1, "a", 3, "f", 5, "g", 6, "z"));
626+
new TreeMap<>(ImmutableSortedMap.of(1, "a", 3, "f", 5, "g", 6, "z"));
624627

625628
SortedMapDifference<Integer, String> diff1 = Maps.difference(left, right);
626629
left.put(6, "z");
@@ -1377,9 +1380,128 @@ public String transformEntry(String key, String value) {
13771380
assertEquals(ImmutableSortedMap.of("a", "a4", "b", "b9"), transformed);
13781381
}
13791382

1383+
@GwtIncompatible // NavigableMap
1384+
public void testFilteredNavigableMapPollFirstEntry() {
1385+
NavigableMap<Integer, String> unfiltered = new TreeMap<>();
1386+
unfiltered.put(1, "one");
1387+
unfiltered.put(2, "two");
1388+
unfiltered.put(3, "three");
1389+
NavigableMap<Integer, String> filtered = filterKeys(unfiltered, k -> k != 1);
1390+
1391+
// 2 is the root of the TreeMap, so removing it moves another mapping into its entry object.
1392+
assertThat(filtered.pollFirstEntry()).isEqualTo(immutableEntry(2, "two"));
1393+
assertThat(unfiltered).containsExactly(1, "one", 3, "three").inOrder();
1394+
}
1395+
1396+
@GwtIncompatible // NavigableMap
1397+
public void testFilteredNavigableMapPollFirstDrainsInOrder() {
1398+
NavigableMap<Integer, String> unfiltered = new TreeMap<>();
1399+
for (int i = 0; i < 10; i++) {
1400+
unfiltered.put(i, Integer.toString(i));
1401+
}
1402+
NavigableMap<Integer, String> filtered = filterKeys(unfiltered, k -> k % 2 == 1);
1403+
1404+
List<Entry<Integer, String>> polled = new ArrayList<>();
1405+
Entry<Integer, String> entry;
1406+
while ((entry = filtered.pollFirstEntry()) != null) {
1407+
polled.add(entry);
1408+
}
1409+
1410+
assertThat(polled)
1411+
.containsExactly(
1412+
immutableEntry(1, "1"),
1413+
immutableEntry(3, "3"),
1414+
immutableEntry(5, "5"),
1415+
immutableEntry(7, "7"),
1416+
immutableEntry(9, "9"))
1417+
.inOrder();
1418+
assertThat(unfiltered.keySet()).containsExactly(0, 2, 4, 6, 8).inOrder();
1419+
}
1420+
1421+
@GwtIncompatible // NavigableMap
1422+
public void testFilteredNavigableMapPollLastDrainsInOrder() {
1423+
NavigableMap<Integer, String> unfiltered = new TreeMap<>();
1424+
for (int i = 0; i < 10; i++) {
1425+
unfiltered.put(i, Integer.toString(i));
1426+
}
1427+
NavigableMap<Integer, String> filtered = filterKeys(unfiltered, k -> k % 2 == 1);
1428+
1429+
List<Entry<Integer, String>> polled = new ArrayList<>();
1430+
Entry<Integer, String> entry;
1431+
while ((entry = filtered.pollLastEntry()) != null) {
1432+
polled.add(entry);
1433+
}
1434+
1435+
assertThat(polled)
1436+
.containsExactly(
1437+
immutableEntry(9, "9"),
1438+
immutableEntry(7, "7"),
1439+
immutableEntry(5, "5"),
1440+
immutableEntry(3, "3"),
1441+
immutableEntry(1, "1"))
1442+
.inOrder();
1443+
assertThat(unfiltered.keySet()).containsExactly(0, 2, 4, 6, 8).inOrder();
1444+
}
1445+
1446+
@GwtIncompatible // NavigableMap
1447+
public void testFilteredNavigableMapNavigationEntriesAreSnapshots() {
1448+
NavigableMap<Integer, String> unfiltered = new TreeMap<>();
1449+
unfiltered.put(1, "one");
1450+
unfiltered.put(2, "two");
1451+
unfiltered.put(3, "three");
1452+
unfiltered.put(4, "four");
1453+
NavigableMap<Integer, String> filtered = filterValues(unfiltered, v -> !v.equals("forbidden"));
1454+
1455+
List<Entry<Integer, String>> entries =
1456+
asList(
1457+
filtered.firstEntry(),
1458+
filtered.lastEntry(),
1459+
filtered.ceilingEntry(2),
1460+
filtered.floorEntry(2),
1461+
filtered.higherEntry(2),
1462+
filtered.lowerEntry(2),
1463+
filtered.descendingMap().firstEntry(),
1464+
filtered.descendingMap().lastEntry(),
1465+
filtered.headMap(3, true).lastEntry());
1466+
for (Entry<Integer, String> entry : entries) {
1467+
assertThrows(UnsupportedOperationException.class, () -> entry.setValue("forbidden"));
1468+
assertThrows(UnsupportedOperationException.class, () -> entry.setValue("allowed"));
1469+
}
1470+
assertThat(unfiltered).containsExactly(1, "one", 2, "two", 3, "three", 4, "four").inOrder();
1471+
1472+
Entry<Integer, String> polledFirst = filtered.pollFirstEntry();
1473+
assertThrows(UnsupportedOperationException.class, () -> polledFirst.setValue("forbidden"));
1474+
assertThrows(UnsupportedOperationException.class, () -> polledFirst.setValue("allowed"));
1475+
1476+
Entry<Integer, String> polledLast = filtered.pollLastEntry();
1477+
assertThrows(UnsupportedOperationException.class, () -> polledLast.setValue("forbidden"));
1478+
assertThrows(UnsupportedOperationException.class, () -> polledLast.setValue("allowed"));
1479+
}
1480+
1481+
@GwtIncompatible // NavigableMap
1482+
public void testFilteredNavigableMapIterationEntriesAreLive() {
1483+
NavigableMap<Integer, String> unfiltered = new TreeMap<>();
1484+
unfiltered.put(1, "one");
1485+
unfiltered.put(2, "two");
1486+
unfiltered.put(3, "three");
1487+
unfiltered.put(4, "four");
1488+
NavigableMap<Integer, String> filtered = filterValues(unfiltered, v -> !v.equals("forbidden"));
1489+
1490+
Entry<Integer, String> liveEntry = filtered.entrySet().iterator().next();
1491+
assertThrows(IllegalArgumentException.class, () -> liveEntry.setValue("forbidden"));
1492+
liveEntry.setValue("uno");
1493+
assertThat(unfiltered).containsEntry(1, "uno");
1494+
1495+
Entry<Integer, String> liveDescendingEntry =
1496+
filtered.descendingMap().entrySet().iterator().next();
1497+
assertThrows(IllegalArgumentException.class, () -> liveDescendingEntry.setValue("forbidden"));
1498+
liveDescendingEntry.setValue("cuatro");
1499+
assertThat(unfiltered).containsEntry(4, "cuatro");
1500+
}
1501+
13801502
@GwtIncompatible // NavigableMap
13811503
public void testUnmodifiableNavigableMap() {
1382-
TreeMap<Integer, String> mod = Maps.newTreeMap();
1504+
TreeMap<Integer, String> mod = new TreeMap<>();
13831505
mod.put(1, "one");
13841506
mod.put(2, "two");
13851507
mod.put(3, "three");

0 commit comments

Comments
 (0)
⌂ 换网址