aboutsummaryrefslogtreecommitdiff
path: root/guava/src/com/google/common/collect/AbstractMapBasedMultimap.java
blob: d9108f16c7f70b135ac042c765ce78e6549053c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
/*
 * Copyright (C) 2007 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.common.collect;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import static java.util.Objects.requireNonNull;

import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Maps.ViewCachingAbstractMap;
import com.google.j2objc.annotations.WeakOuter;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.RandomAccess;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.Spliterator;
import java.util.function.BiConsumer;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * Basic implementation of the {@link Multimap} interface. This class represents a multimap as a map
 * that associates each key with a collection of values. All methods of {@link Multimap} are
 * supported, including those specified as optional in the interface.
 *
 * <p>To implement a multimap, a subclass must define the method {@link #createCollection()}, which
 * creates an empty collection of values for a key.
 *
 * <p>The multimap constructor takes a map that has a single entry for each distinct key. When you
 * insert a key-value pair with a key that isn't already in the multimap, {@code
 * AbstractMapBasedMultimap} calls {@link #createCollection()} to create the collection of values
 * for that key. The subclass should not call {@link #createCollection()} directly, and a new
 * instance should be created every time the method is called.
 *
 * <p>For example, the subclass could pass a {@link java.util.TreeMap} during construction, and
 * {@link #createCollection()} could return a {@link java.util.TreeSet}, in which case the
 * multimap's iterators would propagate through the keys and values in sorted order.
 *
 * <p>Keys and values may be null, as long as the underlying collection classes support null
 * elements.
 *
 * <p>The collections created by {@link #createCollection()} may or may not allow duplicates. If the
 * collection, such as a {@link Set}, does not support duplicates, an added key-value pair will
 * replace an existing pair with the same key and value, if such a pair is present. With collections
 * like {@link List} that allow duplicates, the collection will keep the existing key-value pairs
 * while adding a new pair.
 *
 * <p>This class is not threadsafe when any concurrent operations update the multimap, even if the
 * underlying map and {@link #createCollection()} method return threadsafe classes. Concurrent read
 * operations will work correctly. To allow concurrent update operations, wrap your multimap with a
 * call to {@link Multimaps#synchronizedMultimap}.
 *
 * <p>For serialization to work, the subclass must specify explicit {@code readObject} and {@code
 * writeObject} methods.
 *
 * @author Jared Levy
 * @author Louis Wasserman
 */
@GwtCompatible
@ElementTypesAreNonnullByDefault
abstract class AbstractMapBasedMultimap<K extends @Nullable Object, V extends @Nullable Object>
    extends AbstractMultimap<K, V> implements Serializable {
  /*
   * Here's an outline of the overall design.
   *
   * The map variable contains the collection of values associated with each
   * key. When a key-value pair is added to a multimap that didn't previously
   * contain any values for that key, a new collection generated by
   * createCollection is added to the map. That same collection instance
   * remains in the map as long as the multimap has any values for the key. If
   * all values for the key are removed, the key and collection are removed
   * from the map.
   *
   * The get method returns a WrappedCollection, which decorates the collection
   * in the map (if the key is present) or an empty collection (if the key is
   * not present). When the collection delegate in the WrappedCollection is
   * empty, the multimap may contain subsequently added values for that key. To
   * handle that situation, the WrappedCollection checks whether map contains
   * an entry for the provided key, and if so replaces the delegate.
   */

  private transient Map<K, Collection<V>> map;
  private transient int totalSize;

  /**
   * Creates a new multimap that uses the provided map.
   *
   * @param map place to store the mapping from each key to its corresponding values
   * @throws IllegalArgumentException if {@code map} is not empty
   */
  protected AbstractMapBasedMultimap(Map<K, Collection<V>> map) {
    checkArgument(map.isEmpty());
    this.map = map;
  }

  /** Used during deserialization only. */
  final void setMap(Map<K, Collection<V>> map) {
    this.map = map;
    totalSize = 0;
    for (Collection<V> values : map.values()) {
      checkArgument(!values.isEmpty());
      totalSize += values.size();
    }
  }

  /**
   * Creates an unmodifiable, empty collection of values.
   *
   * <p>This is used in {@link #removeAll} on an empty key.
   */
  Collection<V> createUnmodifiableEmptyCollection() {
    return unmodifiableCollectionSubclass(createCollection());
  }

  /**
   * Creates the collection of values for a single key.
   *
   * <p>Collections with weak, soft, or phantom references are not supported. Each call to {@code
   * createCollection} should create a new instance.
   *
   * <p>The returned collection class determines whether duplicate key-value pairs are allowed.
   *
   * @return an empty collection of values
   */
  abstract Collection<V> createCollection();

  /**
   * Creates the collection of values for an explicitly provided key. By default, it simply calls
   * {@link #createCollection()}, which is the correct behavior for most implementations. The {@link
   * LinkedHashMultimap} class overrides it.
   *
   * @param key key to associate with values in the collection
   * @return an empty collection of values
   */
  Collection<V> createCollection(@ParametricNullness K key) {
    return createCollection();
  }

  Map<K, Collection<V>> backingMap() {
    return map;
  }

  // Query Operations

  @Override
  public int size() {
    return totalSize;
  }

  @Override
  public boolean containsKey(@CheckForNull Object key) {
    return map.containsKey(key);
  }

  // Modification Operations

  @Override
  public boolean put(@ParametricNullness K key, @ParametricNullness V value) {
    Collection<V> collection = map.get(key);
    if (collection == null) {
      collection = createCollection(key);
      if (collection.add(value)) {
        totalSize++;
        map.put(key, collection);
        return true;
      } else {
        throw new AssertionError("New Collection violated the Collection spec");
      }
    } else if (collection.add(value)) {
      totalSize++;
      return true;
    } else {
      return false;
    }
  }

  private Collection<V> getOrCreateCollection(@ParametricNullness K key) {
    Collection<V> collection = map.get(key);
    if (collection == null) {
      collection = createCollection(key);
      map.put(key, collection);
    }
    return collection;
  }

  // Bulk Operations

  /**
   * {@inheritDoc}
   *
   * <p>The returned collection is immutable.
   */
  @Override
  public Collection<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) {
    Iterator<? extends V> iterator = values.iterator();
    if (!iterator.hasNext()) {
      return removeAll(key);
    }

    // TODO(lowasser): investigate atomic failure?
    Collection<V> collection = getOrCreateCollection(key);
    Collection<V> oldValues = createCollection();
    oldValues.addAll(collection);

    totalSize -= collection.size();
    collection.clear();

    while (iterator.hasNext()) {
      if (collection.add(iterator.next())) {
        totalSize++;
      }
    }

    return unmodifiableCollectionSubclass(oldValues);
  }

  /**
   * {@inheritDoc}
   *
   * <p>The returned collection is immutable.
   */
  @Override
  public Collection<V> removeAll(@CheckForNull Object key) {
    Collection<V> collection = map.remove(key);

    if (collection == null) {
      return createUnmodifiableEmptyCollection();
    }

    Collection<V> output = createCollection();
    output.addAll(collection);
    totalSize -= collection.size();
    collection.clear();

    return unmodifiableCollectionSubclass(output);
  }

  <E extends @Nullable Object> Collection<E> unmodifiableCollectionSubclass(
      Collection<E> collection) {
    return Collections.unmodifiableCollection(collection);
  }

  @Override
  public void clear() {
    // Clear each collection, to make previously returned collections empty.
    for (Collection<V> collection : map.values()) {
      collection.clear();
    }
    map.clear();
    totalSize = 0;
  }

  // Views

  /**
   * {@inheritDoc}
   *
   * <p>The returned collection is not serializable.
   */
  @Override
  public Collection<V> get(@ParametricNullness K key) {
    Collection<V> collection = map.get(key);
    if (collection == null) {
      collection = createCollection(key);
    }
    return wrapCollection(key, collection);
  }

  /**
   * Generates a decorated collection that remains consistent with the values in the multimap for
   * the provided key. Changes to the multimap may alter the returned collection, and vice versa.
   */
  Collection<V> wrapCollection(@ParametricNullness K key, Collection<V> collection) {
    return new WrappedCollection(key, collection, null);
  }

  final List<V> wrapList(
      @ParametricNullness K key, List<V> list, @CheckForNull WrappedCollection ancestor) {
    return (list instanceof RandomAccess)
        ? new RandomAccessWrappedList(key, list, ancestor)
        : new WrappedList(key, list, ancestor);
  }

  /**
   * Collection decorator that stays in sync with the multimap values for a key. There are two kinds
   * of wrapped collections: full and subcollections. Both have a delegate pointing to the
   * underlying collection class.
   *
   * <p>Full collections, identified by a null ancestor field, contain all multimap values for a
   * given key. Its delegate is a value in {@link AbstractMapBasedMultimap#map} whenever the
   * delegate is non-empty. The {@code refreshIfEmpty}, {@code removeIfEmpty}, and {@code addToMap}
   * methods ensure that the {@code WrappedCollection} and map remain consistent.
   *
   * <p>A subcollection, such as a sublist, contains some of the values for a given key. Its
   * ancestor field points to the full wrapped collection with all values for the key. The
   * subcollection {@code refreshIfEmpty}, {@code removeIfEmpty}, and {@code addToMap} methods call
   * the corresponding methods of the full wrapped collection.
   */
  @WeakOuter
  class WrappedCollection extends AbstractCollection<V> {
    @ParametricNullness final K key;
    Collection<V> delegate;
    @CheckForNull final WrappedCollection ancestor;
    @CheckForNull final Collection<V> ancestorDelegate;

    WrappedCollection(
        @ParametricNullness K key,
        Collection<V> delegate,
        @CheckForNull WrappedCollection ancestor) {
      this.key = key;
      this.delegate = delegate;
      this.ancestor = ancestor;
      this.ancestorDelegate = (ancestor == null) ? null : ancestor.getDelegate();
    }

    /**
     * If the delegate collection is empty, but the multimap has values for the key, replace the
     * delegate with the new collection for the key.
     *
     * <p>For a subcollection, refresh its ancestor and validate that the ancestor delegate hasn't
     * changed.
     */
    void refreshIfEmpty() {
      if (ancestor != null) {
        ancestor.refreshIfEmpty();
        if (ancestor.getDelegate() != ancestorDelegate) {
          throw new ConcurrentModificationException();
        }
      } else if (delegate.isEmpty()) {
        Collection<V> newDelegate = map.get(key);
        if (newDelegate != null) {
          delegate = newDelegate;
        }
      }
    }

    /**
     * If collection is empty, remove it from {@code AbstractMapBasedMultimap.this.map}. For
     * subcollections, check whether the ancestor collection is empty.
     */
    void removeIfEmpty() {
      if (ancestor != null) {
        ancestor.removeIfEmpty();
      } else if (delegate.isEmpty()) {
        map.remove(key);
      }
    }

    @ParametricNullness
    K getKey() {
      return key;
    }

    /**
     * Add the delegate to the map. Other {@code WrappedCollection} methods should call this method
     * after adding elements to a previously empty collection.
     *
     * <p>Subcollection add the ancestor's delegate instead.
     */
    void addToMap() {
      if (ancestor != null) {
        ancestor.addToMap();
      } else {
        map.put(key, delegate);
      }
    }

    @Override
    public int size() {
      refreshIfEmpty();
      return delegate.size();
    }

    @Override
    public boolean equals(@CheckForNull Object object) {
      if (object == this) {
        return true;
      }
      refreshIfEmpty();
      return delegate.equals(object);
    }

    @Override
    public int hashCode() {
      refreshIfEmpty();
      return delegate.hashCode();
    }

    @Override
    public String toString() {
      refreshIfEmpty();
      return delegate.toString();
    }

    Collection<V> getDelegate() {
      return delegate;
    }

    @Override
    public Iterator<V> iterator() {
      refreshIfEmpty();
      return new WrappedIterator();
    }

    @Override
    public Spliterator<V> spliterator() {
      refreshIfEmpty();
      return delegate.spliterator();
    }

    /** Collection iterator for {@code WrappedCollection}. */
    class WrappedIterator implements Iterator<V> {
      final Iterator<V> delegateIterator;
      final Collection<V> originalDelegate = delegate;

      WrappedIterator() {
        delegateIterator = iteratorOrListIterator(delegate);
      }

      WrappedIterator(Iterator<V> delegateIterator) {
        this.delegateIterator = delegateIterator;
      }

      /**
       * If the delegate changed since the iterator was created, the iterator is no longer valid.
       */
      void validateIterator() {
        refreshIfEmpty();
        if (delegate != originalDelegate) {
          throw new ConcurrentModificationException();
        }
      }

      @Override
      public boolean hasNext() {
        validateIterator();
        return delegateIterator.hasNext();
      }

      @Override
      @ParametricNullness
      public V next() {
        validateIterator();
        return delegateIterator.next();
      }

      @Override
      public void remove() {
        delegateIterator.remove();
        totalSize--;
        removeIfEmpty();
      }

      Iterator<V> getDelegateIterator() {
        validateIterator();
        return delegateIterator;
      }
    }

    @Override
    public boolean add(@ParametricNullness V value) {
      refreshIfEmpty();
      boolean wasEmpty = delegate.isEmpty();
      boolean changed = delegate.add(value);
      if (changed) {
        totalSize++;
        if (wasEmpty) {
          addToMap();
        }
      }
      return changed;
    }

    @CheckForNull
    WrappedCollection getAncestor() {
      return ancestor;
    }

    // The following methods are provided for better performance.

    @Override
    public boolean addAll(Collection<? extends V> collection) {
      if (collection.isEmpty()) {
        return false;
      }
      int oldSize = size(); // calls refreshIfEmpty
      boolean changed = delegate.addAll(collection);
      if (changed) {
        int newSize = delegate.size();
        totalSize += (newSize - oldSize);
        if (oldSize == 0) {
          addToMap();
        }
      }
      return changed;
    }

    @Override
    public boolean contains(@CheckForNull Object o) {
      refreshIfEmpty();
      return delegate.contains(o);
    }

    @Override
    public boolean containsAll(Collection<?> c) {
      refreshIfEmpty();
      return delegate.containsAll(c);
    }

    @Override
    public void clear() {
      int oldSize = size(); // calls refreshIfEmpty
      if (oldSize == 0) {
        return;
      }
      delegate.clear();
      totalSize -= oldSize;
      removeIfEmpty(); // maybe shouldn't be removed if this is a sublist
    }

    @Override
    public boolean remove(@CheckForNull Object o) {
      refreshIfEmpty();
      boolean changed = delegate.remove(o);
      if (changed) {
        totalSize--;
        removeIfEmpty();
      }
      return changed;
    }

    @Override
    public boolean removeAll(Collection<?> c) {
      if (c.isEmpty()) {
        return false;
      }
      int oldSize = size(); // calls refreshIfEmpty
      boolean changed = delegate.removeAll(c);
      if (changed) {
        int newSize = delegate.size();
        totalSize += (newSize - oldSize);
        removeIfEmpty();
      }
      return changed;
    }

    @Override
    public boolean retainAll(Collection<?> c) {
      checkNotNull(c);
      int oldSize = size(); // calls refreshIfEmpty
      boolean changed = delegate.retainAll(c);
      if (changed) {
        int newSize = delegate.size();
        totalSize += (newSize - oldSize);
        removeIfEmpty();
      }
      return changed;
    }
  }

  private static <E extends @Nullable Object> Iterator<E> iteratorOrListIterator(
      Collection<E> collection) {
    return (collection instanceof List)
        ? ((List<E>) collection).listIterator()
        : collection.iterator();
  }

  /** Set decorator that stays in sync with the multimap values for a key. */
  @WeakOuter
  class WrappedSet extends WrappedCollection implements Set<V> {
    WrappedSet(@ParametricNullness K key, Set<V> delegate) {
      super(key, delegate, null);
    }

    @Override
    public boolean removeAll(Collection<?> c) {
      if (c.isEmpty()) {
        return false;
      }
      int oldSize = size(); // calls refreshIfEmpty

      // Guava issue 1013: AbstractSet and most JDK set implementations are
      // susceptible to quadratic removeAll performance on lists;
      // use a slightly smarter implementation here
      boolean changed = Sets.removeAllImpl((Set<V>) delegate, c);
      if (changed) {
        int newSize = delegate.size();
        totalSize += (newSize - oldSize);
        removeIfEmpty();
      }
      return changed;
    }
  }

  /** SortedSet decorator that stays in sync with the multimap values for a key. */
  @WeakOuter
  class WrappedSortedSet extends WrappedCollection implements SortedSet<V> {
    WrappedSortedSet(
        @ParametricNullness K key,
        SortedSet<V> delegate,
        @CheckForNull WrappedCollection ancestor) {
      super(key, delegate, ancestor);
    }

    SortedSet<V> getSortedSetDelegate() {
      return (SortedSet<V>) getDelegate();
    }

    @Override
    @CheckForNull
    public Comparator<? super V> comparator() {
      return getSortedSetDelegate().comparator();
    }

    @Override
    @ParametricNullness
    public V first() {
      refreshIfEmpty();
      return getSortedSetDelegate().first();
    }

    @Override
    @ParametricNullness
    public V last() {
      refreshIfEmpty();
      return getSortedSetDelegate().last();
    }

    @Override
    public SortedSet<V> headSet(@ParametricNullness V toElement) {
      refreshIfEmpty();
      return new WrappedSortedSet(
          getKey(),
          getSortedSetDelegate().headSet(toElement),
          (getAncestor() == null) ? this : getAncestor());
    }

    @Override
    public SortedSet<V> subSet(@ParametricNullness V fromElement, @ParametricNullness V toElement) {
      refreshIfEmpty();
      return new WrappedSortedSet(
          getKey(),
          getSortedSetDelegate().subSet(fromElement, toElement),
          (getAncestor() == null) ? this : getAncestor());
    }

    @Override
    public SortedSet<V> tailSet(@ParametricNullness V fromElement) {
      refreshIfEmpty();
      return new WrappedSortedSet(
          getKey(),
          getSortedSetDelegate().tailSet(fromElement),
          (getAncestor() == null) ? this : getAncestor());
    }
  }

  @WeakOuter
  class WrappedNavigableSet extends WrappedSortedSet implements NavigableSet<V> {
    WrappedNavigableSet(
        @ParametricNullness K key,
        NavigableSet<V> delegate,
        @CheckForNull WrappedCollection ancestor) {
      super(key, delegate, ancestor);
    }

    @Override
    NavigableSet<V> getSortedSetDelegate() {
      return (NavigableSet<V>) super.getSortedSetDelegate();
    }

    @Override
    @CheckForNull
    public V lower(@ParametricNullness V v) {
      return getSortedSetDelegate().lower(v);
    }

    @Override
    @CheckForNull
    public V floor(@ParametricNullness V v) {
      return getSortedSetDelegate().floor(v);
    }

    @Override
    @CheckForNull
    public V ceiling(@ParametricNullness V v) {
      return getSortedSetDelegate().ceiling(v);
    }

    @Override
    @CheckForNull
    public V higher(@ParametricNullness V v) {
      return getSortedSetDelegate().higher(v);
    }

    @Override
    @CheckForNull
    public V pollFirst() {
      return Iterators.pollNext(iterator());
    }

    @Override
    @CheckForNull
    public V pollLast() {
      return Iterators.pollNext(descendingIterator());
    }

    private NavigableSet<V> wrap(NavigableSet<V> wrapped) {
      return new WrappedNavigableSet(key, wrapped, (getAncestor() == null) ? this : getAncestor());
    }

    @Override
    public NavigableSet<V> descendingSet() {
      return wrap(getSortedSetDelegate().descendingSet());
    }

    @Override
    public Iterator<V> descendingIterator() {
      return new WrappedIterator(getSortedSetDelegate().descendingIterator());
    }

    @Override
    public NavigableSet<V> subSet(
        @ParametricNullness V fromElement,
        boolean fromInclusive,
        @ParametricNullness V toElement,
        boolean toInclusive) {
      return wrap(
          getSortedSetDelegate().subSet(fromElement, fromInclusive, toElement, toInclusive));
    }

    @Override
    public NavigableSet<V> headSet(@ParametricNullness V toElement, boolean inclusive) {
      return wrap(getSortedSetDelegate().headSet(toElement, inclusive));
    }

    @Override
    public NavigableSet<V> tailSet(@ParametricNullness V fromElement, boolean inclusive) {
      return wrap(getSortedSetDelegate().tailSet(fromElement, inclusive));
    }
  }

  /** List decorator that stays in sync with the multimap values for a key. */
  @WeakOuter
  class WrappedList extends WrappedCollection implements List<V> {
    WrappedList(
        @ParametricNullness K key, List<V> delegate, @CheckForNull WrappedCollection ancestor) {
      super(key, delegate, ancestor);
    }

    List<V> getListDelegate() {
      return (List<V>) getDelegate();
    }

    @Override
    public boolean addAll(int index, Collection<? extends V> c) {
      if (c.isEmpty()) {
        return false;
      }
      int oldSize = size(); // calls refreshIfEmpty
      boolean changed = getListDelegate().addAll(index, c);
      if (changed) {
        int newSize = getDelegate().size();
        totalSize += (newSize - oldSize);
        if (oldSize == 0) {
          addToMap();
        }
      }
      return changed;
    }

    @Override
    @ParametricNullness
    public V get(int index) {
      refreshIfEmpty();
      return getListDelegate().get(index);
    }

    @Override
    @ParametricNullness
    public V set(int index, @ParametricNullness V element) {
      refreshIfEmpty();
      return getListDelegate().set(index, element);
    }

    @Override
    public void add(int index, @ParametricNullness V element) {
      refreshIfEmpty();
      boolean wasEmpty = getDelegate().isEmpty();
      getListDelegate().add(index, element);
      totalSize++;
      if (wasEmpty) {
        addToMap();
      }
    }

    @Override
    @ParametricNullness
    public V remove(int index) {
      refreshIfEmpty();
      V value = getListDelegate().remove(index);
      totalSize--;
      removeIfEmpty();
      return value;
    }

    @Override
    public int indexOf(@CheckForNull Object o) {
      refreshIfEmpty();
      return getListDelegate().indexOf(o);
    }

    @Override
    public int lastIndexOf(@CheckForNull Object o) {
      refreshIfEmpty();
      return getListDelegate().lastIndexOf(o);
    }

    @Override
    public ListIterator<V> listIterator() {
      refreshIfEmpty();
      return new WrappedListIterator();
    }

    @Override
    public ListIterator<V> listIterator(int index) {
      refreshIfEmpty();
      return new WrappedListIterator(index);
    }

    @Override
    public List<V> subList(int fromIndex, int toIndex) {
      refreshIfEmpty();
      return wrapList(
          getKey(),
          getListDelegate().subList(fromIndex, toIndex),
          (getAncestor() == null) ? this : getAncestor());
    }

    /** ListIterator decorator. */
    private class WrappedListIterator extends WrappedIterator implements ListIterator<V> {
      WrappedListIterator() {}

      public WrappedListIterator(int index) {
        super(getListDelegate().listIterator(index));
      }

      private ListIterator<V> getDelegateListIterator() {
        return (ListIterator<V>) getDelegateIterator();
      }

      @Override
      public boolean hasPrevious() {
        return getDelegateListIterator().hasPrevious();
      }

      @Override
      @ParametricNullness
      public V previous() {
        return getDelegateListIterator().previous();
      }

      @Override
      public int nextIndex() {
        return getDelegateListIterator().nextIndex();
      }

      @Override
      public int previousIndex() {
        return getDelegateListIterator().previousIndex();
      }

      @Override
      public void set(@ParametricNullness V value) {
        getDelegateListIterator().set(value);
      }

      @Override
      public void add(@ParametricNullness V value) {
        boolean wasEmpty = isEmpty();
        getDelegateListIterator().add(value);
        totalSize++;
        if (wasEmpty) {
          addToMap();
        }
      }
    }
  }

  /**
   * List decorator that stays in sync with the multimap values for a key and supports rapid random
   * access.
   */
  private class RandomAccessWrappedList extends WrappedList implements RandomAccess {
    RandomAccessWrappedList(
        @ParametricNullness K key, List<V> delegate, @CheckForNull WrappedCollection ancestor) {
      super(key, delegate, ancestor);
    }
  }

  @Override
  Set<K> createKeySet() {
    return new KeySet(map);
  }

  final Set<K> createMaybeNavigableKeySet() {
    if (map instanceof NavigableMap) {
      return new NavigableKeySet((NavigableMap<K, Collection<V>>) map);
    } else if (map instanceof SortedMap) {
      return new SortedKeySet((SortedMap<K, Collection<V>>) map);
    } else {
      return new KeySet(map);
    }
  }

  @WeakOuter
  private class KeySet extends Maps.KeySet<K, Collection<V>> {
    KeySet(final Map<K, Collection<V>> subMap) {
      super(subMap);
    }

    @Override
    public Iterator<K> iterator() {
      final Iterator<Entry<K, Collection<V>>> entryIterator = map().entrySet().iterator();
      return new Iterator<K>() {
        @CheckForNull Entry<K, Collection<V>> entry;

        @Override
        public boolean hasNext() {
          return entryIterator.hasNext();
        }

        @Override
        @ParametricNullness
        public K next() {
          entry = entryIterator.next();
          return entry.getKey();
        }

        @Override
        public void remove() {
          checkState(entry != null, "no calls to next() since the last call to remove()");
          Collection<V> collection = entry.getValue();
          entryIterator.remove();
          totalSize -= collection.size();
          collection.clear();
          entry = null;
        }
      };
    }

    // The following methods are included for better performance.

    @Override
    public Spliterator<K> spliterator() {
      return map().keySet().spliterator();
    }

    @Override
    public boolean remove(@CheckForNull Object key) {
      int count = 0;
      Collection<V> collection = map().remove(key);
      if (collection != null) {
        count = collection.size();
        collection.clear();
        totalSize -= count;
      }
      return count > 0;
    }

    @Override
    public void clear() {
      Iterators.clear(iterator());
    }

    @Override
    public boolean containsAll(Collection<?> c) {
      return map().keySet().containsAll(c);
    }

    @Override
    public boolean equals(@CheckForNull Object object) {
      return this == object || this.map().keySet().equals(object);
    }

    @Override
    public int hashCode() {
      return map().keySet().hashCode();
    }
  }

  @WeakOuter
  private class SortedKeySet extends KeySet implements SortedSet<K> {

    SortedKeySet(SortedMap<K, Collection<V>> subMap) {
      super(subMap);
    }

    SortedMap<K, Collection<V>> sortedMap() {
      return (SortedMap<K, Collection<V>>) super.map();
    }

    @Override
    @CheckForNull
    public Comparator<? super K> comparator() {
      return sortedMap().comparator();
    }

    @Override
    @ParametricNullness
    public K first() {
      return sortedMap().firstKey();
    }

    @Override
    public SortedSet<K> headSet(@ParametricNullness K toElement) {
      return new SortedKeySet(sortedMap().headMap(toElement));
    }

    @Override
    @ParametricNullness
    public K last() {
      return sortedMap().lastKey();
    }

    @Override
    public SortedSet<K> subSet(@ParametricNullness K fromElement, @ParametricNullness K toElement) {
      return new SortedKeySet(sortedMap().subMap(fromElement, toElement));
    }

    @Override
    public SortedSet<K> tailSet(@ParametricNullness K fromElement) {
      return new SortedKeySet(sortedMap().tailMap(fromElement));
    }
  }

  @WeakOuter
  private final class NavigableKeySet extends SortedKeySet implements NavigableSet<K> {
    NavigableKeySet(NavigableMap<K, Collection<V>> subMap) {
      super(subMap);
    }

    @Override
    NavigableMap<K, Collection<V>> sortedMap() {
      return (NavigableMap<K, Collection<V>>) super.sortedMap();
    }

    @Override
    @CheckForNull
    public K lower(@ParametricNullness K k) {
      return sortedMap().lowerKey(k);
    }

    @Override
    @CheckForNull
    public K floor(@ParametricNullness K k) {
      return sortedMap().floorKey(k);
    }

    @Override
    @CheckForNull
    public K ceiling(@ParametricNullness K k) {
      return sortedMap().ceilingKey(k);
    }

    @Override
    @CheckForNull
    public K higher(@ParametricNullness K k) {
      return sortedMap().higherKey(k);
    }

    @Override
    @CheckForNull
    public K pollFirst() {
      return Iterators.pollNext(iterator());
    }

    @Override
    @CheckForNull
    public K pollLast() {
      return Iterators.pollNext(descendingIterator());
    }

    @Override
    public NavigableSet<K> descendingSet() {
      return new NavigableKeySet(sortedMap().descendingMap());
    }

    @Override
    public Iterator<K> descendingIterator() {
      return descendingSet().iterator();
    }

    @Override
    public NavigableSet<K> headSet(@ParametricNullness K toElement) {
      return headSet(toElement, false);
    }

    @Override
    public NavigableSet<K> headSet(@ParametricNullness K toElement, boolean inclusive) {
      return new NavigableKeySet(sortedMap().headMap(toElement, inclusive));
    }

    @Override
    public NavigableSet<K> subSet(
        @ParametricNullness K fromElement, @ParametricNullness K toElement) {
      return subSet(fromElement, true, toElement, false);
    }

    @Override
    public NavigableSet<K> subSet(
        @ParametricNullness K fromElement,
        boolean fromInclusive,
        @ParametricNullness K toElement,
        boolean toInclusive) {
      return new NavigableKeySet(
          sortedMap().subMap(fromElement, fromInclusive, toElement, toInclusive));
    }

    @Override
    public NavigableSet<K> tailSet(@ParametricNullness K fromElement) {
      return tailSet(fromElement, true);
    }

    @Override
    public NavigableSet<K> tailSet(@ParametricNullness K fromElement, boolean inclusive) {
      return new NavigableKeySet(sortedMap().tailMap(fromElement, inclusive));
    }
  }

  /** Removes all values for the provided key. */
  private void removeValuesForKey(@CheckForNull Object key) {
    Collection<V> collection = Maps.safeRemove(map, key);

    if (collection != null) {
      int count = collection.size();
      collection.clear();
      totalSize -= count;
    }
  }

  private abstract class Itr<T extends @Nullable Object> implements Iterator<T> {
    final Iterator<Entry<K, Collection<V>>> keyIterator;
    @CheckForNull K key;
    @CheckForNull Collection<V> collection;
    Iterator<V> valueIterator;

    Itr() {
      keyIterator = map.entrySet().iterator();
      key = null;
      collection = null;
      valueIterator = Iterators.emptyModifiableIterator();
    }

    abstract T output(@ParametricNullness K key, @ParametricNullness V value);

    @Override
    public boolean hasNext() {
      return keyIterator.hasNext() || valueIterator.hasNext();
    }

    @Override
    @ParametricNullness
    public T next() {
      if (!valueIterator.hasNext()) {
        Entry<K, Collection<V>> mapEntry = keyIterator.next();
        key = mapEntry.getKey();
        collection = mapEntry.getValue();
        valueIterator = collection.iterator();
      }
      /*
       * uncheckedCastNullableTToT is safe: The first call to this method always enters the !hasNext() case and
       * populates key, after which it's never cleared.
       */
      return output(uncheckedCastNullableTToT(key), valueIterator.next());
    }

    @Override
    public void remove() {
      valueIterator.remove();
      /*
       * requireNonNull is safe because we've already initialized `collection`. If we hadn't, then
       * valueIterator.remove() would have failed.
       */
      if (requireNonNull(collection).isEmpty()) {
        keyIterator.remove();
      }
      totalSize--;
    }
  }

  /**
   * {@inheritDoc}
   *
   * <p>The iterator generated by the returned collection traverses the values for one key, followed
   * by the values of a second key, and so on.
   */
  @Override
  public Collection<V> values() {
    return super.values();
  }

  @Override
  Collection<V> createValues() {
    return new Values();
  }

  @Override
  Iterator<V> valueIterator() {
    return new Itr<V>() {
      @Override
      @ParametricNullness
      V output(@ParametricNullness K key, @ParametricNullness V value) {
        return value;
      }
    };
  }

  @Override
  Spliterator<V> valueSpliterator() {
    return CollectSpliterators.flatMap(
        map.values().spliterator(), Collection::spliterator, Spliterator.SIZED, size());
  }

  /*
   * TODO(kevinb): should we copy this javadoc to each concrete class, so that
   * classes like LinkedHashMultimap that need to say something different are
   * still able to {@inheritDoc} all the way from Multimap?
   */

  @Override
  Multiset<K> createKeys() {
    return new Multimaps.Keys<K, V>(this);
  }

  /**
   * {@inheritDoc}
   *
   * <p>The iterator generated by the returned collection traverses the values for one key, followed
   * by the values of a second key, and so on.
   *
   * <p>Each entry is an immutable snapshot of a key-value mapping in the multimap, taken at the
   * time the entry is returned by a method call to the collection or its iterator.
   */
  @Override
  public Collection<Entry<K, V>> entries() {
    return super.entries();
  }

  @Override
  Collection<Entry<K, V>> createEntries() {
    if (this instanceof SetMultimap) {
      return new EntrySet();
    } else {
      return new Entries();
    }
  }

  /**
   * Returns an iterator across all key-value map entries, used by {@code entries().iterator()} and
   * {@code values().iterator()}. The default behavior, which traverses the values for one key, the
   * values for a second key, and so on, suffices for most {@code AbstractMapBasedMultimap}
   * implementations.
   *
   * @return an iterator across map entries
   */
  @Override
  Iterator<Entry<K, V>> entryIterator() {
    return new Itr<Entry<K, V>>() {
      @Override
      Entry<K, V> output(@ParametricNullness K key, @ParametricNullness V value) {
        return Maps.immutableEntry(key, value);
      }
    };
  }

  @Override
  Spliterator<Entry<K, V>> entrySpliterator() {
    return CollectSpliterators.flatMap(
        map.entrySet().spliterator(),
        keyToValueCollectionEntry -> {
          K key = keyToValueCollectionEntry.getKey();
          Collection<V> valueCollection = keyToValueCollectionEntry.getValue();
          return CollectSpliterators.map(
              valueCollection.spliterator(), (V value) -> Maps.immutableEntry(key, value));
        },
        Spliterator.SIZED,
        size());
  }

  @Override
  public void forEach(BiConsumer<? super K, ? super V> action) {
    checkNotNull(action);
    map.forEach(
        (key, valueCollection) -> valueCollection.forEach(value -> action.accept(key, value)));
  }

  @Override
  Map<K, Collection<V>> createAsMap() {
    return new AsMap(map);
  }

  final Map<K, Collection<V>> createMaybeNavigableAsMap() {
    if (map instanceof NavigableMap) {
      return new NavigableAsMap((NavigableMap<K, Collection<V>>) map);
    } else if (map instanceof SortedMap) {
      return new SortedAsMap((SortedMap<K, Collection<V>>) map);
    } else {
      return new AsMap(map);
    }
  }

  @WeakOuter
  private class AsMap extends ViewCachingAbstractMap<K, Collection<V>> {
    /**
     * Usually the same as map, but smaller for the headMap(), tailMap(), or subMap() of a
     * SortedAsMap.
     */
    final transient Map<K, Collection<V>> submap;

    AsMap(Map<K, Collection<V>> submap) {
      this.submap = submap;
    }

    @Override
    protected Set<Entry<K, Collection<V>>> createEntrySet() {
      return new AsMapEntries();
    }

    // The following methods are included for performance.

    @Override
    public boolean containsKey(@CheckForNull Object key) {
      return Maps.safeContainsKey(submap, key);
    }

    @Override
    @CheckForNull
    public Collection<V> get(@CheckForNull Object key) {
      Collection<V> collection = Maps.safeGet(submap, key);
      if (collection == null) {
        return null;
      }
      @SuppressWarnings("unchecked")
      K k = (K) key;
      return wrapCollection(k, collection);
    }

    @Override
    public Set<K> keySet() {
      return AbstractMapBasedMultimap.this.keySet();
    }

    @Override
    public int size() {
      return submap.size();
    }

    @Override
    @CheckForNull
    public Collection<V> remove(@CheckForNull Object key) {
      Collection<V> collection = submap.remove(key);
      if (collection == null) {
        return null;
      }

      Collection<V> output = createCollection();
      output.addAll(collection);
      totalSize -= collection.size();
      collection.clear();
      return output;
    }

    @Override
    public boolean equals(@CheckForNull Object object) {
      return this == object || submap.equals(object);
    }

    @Override
    public int hashCode() {
      return submap.hashCode();
    }

    @Override
    public String toString() {
      return submap.toString();
    }

    @Override
    public void clear() {
      if (submap == map) {
        AbstractMapBasedMultimap.this.clear();
      } else {
        Iterators.clear(new AsMapIterator());
      }
    }

    Entry<K, Collection<V>> wrapEntry(Entry<K, Collection<V>> entry) {
      K key = entry.getKey();
      return Maps.immutableEntry(key, wrapCollection(key, entry.getValue()));
    }

    @WeakOuter
    class AsMapEntries extends Maps.EntrySet<K, Collection<V>> {
      @Override
      Map<K, Collection<V>> map() {
        return AsMap.this;
      }

      @Override
      public Iterator<Entry<K, Collection<V>>> iterator() {
        return new AsMapIterator();
      }

      @Override
      public Spliterator<Entry<K, Collection<V>>> spliterator() {
        return CollectSpliterators.map(submap.entrySet().spliterator(), AsMap.this::wrapEntry);
      }

      // The following methods are included for performance.

      @Override
      public boolean contains(@CheckForNull Object o) {
        return Collections2.safeContains(submap.entrySet(), o);
      }

      @Override
      public boolean remove(@CheckForNull Object o) {
        if (!contains(o)) {
          return false;
        }
        // requireNonNull is safe because of the contains check.
        Entry<?, ?> entry = requireNonNull((Entry<?, ?>) o);
        removeValuesForKey(entry.getKey());
        return true;
      }
    }

    /** Iterator across all keys and value collections. */
    class AsMapIterator implements Iterator<Entry<K, Collection<V>>> {
      final Iterator<Entry<K, Collection<V>>> delegateIterator = submap.entrySet().iterator();
      @CheckForNull Collection<V> collection;

      @Override
      public boolean hasNext() {
        return delegateIterator.hasNext();
      }

      @Override
      public Entry<K, Collection<V>> next() {
        Entry<K, Collection<V>> entry = delegateIterator.next();
        collection = entry.getValue();
        return wrapEntry(entry);
      }

      @Override
      public void remove() {
        checkState(collection != null, "no calls to next() since the last call to remove()");
        delegateIterator.remove();
        totalSize -= collection.size();
        collection.clear();
        collection = null;
      }
    }
  }

  @WeakOuter
  private class SortedAsMap extends AsMap implements SortedMap<K, Collection<V>> {
    SortedAsMap(SortedMap<K, Collection<V>> submap) {
      super(submap);
    }

    SortedMap<K, Collection<V>> sortedMap() {
      return (SortedMap<K, Collection<V>>) submap;
    }

    @Override
    @CheckForNull
    public Comparator<? super K> comparator() {
      return sortedMap().comparator();
    }

    @Override
    @ParametricNullness
    public K firstKey() {
      return sortedMap().firstKey();
    }

    @Override
    @ParametricNullness
    public K lastKey() {
      return sortedMap().lastKey();
    }

    @Override
    public SortedMap<K, Collection<V>> headMap(@ParametricNullness K toKey) {
      return new SortedAsMap(sortedMap().headMap(toKey));
    }

    @Override
    public SortedMap<K, Collection<V>> subMap(
        @ParametricNullness K fromKey, @ParametricNullness K toKey) {
      return new SortedAsMap(sortedMap().subMap(fromKey, toKey));
    }

    @Override
    public SortedMap<K, Collection<V>> tailMap(@ParametricNullness K fromKey) {
      return new SortedAsMap(sortedMap().tailMap(fromKey));
    }

    @CheckForNull SortedSet<K> sortedKeySet;

    // returns a SortedSet, even though returning a Set would be sufficient to
    // satisfy the SortedMap.keySet() interface
    @Override
    public SortedSet<K> keySet() {
      SortedSet<K> result = sortedKeySet;
      return (result == null) ? sortedKeySet = createKeySet() : result;
    }

    @Override
    SortedSet<K> createKeySet() {
      return new SortedKeySet(sortedMap());
    }
  }

  private final class NavigableAsMap extends SortedAsMap implements NavigableMap<K, Collection<V>> {

    NavigableAsMap(NavigableMap<K, Collection<V>> submap) {
      super(submap);
    }

    @Override
    NavigableMap<K, Collection<V>> sortedMap() {
      return (NavigableMap<K, Collection<V>>) super.sortedMap();
    }

    @Override
    @CheckForNull
    public Entry<K, Collection<V>> lowerEntry(@ParametricNullness K key) {
      Entry<K, Collection<V>> entry = sortedMap().lowerEntry(key);
      return (entry == null) ? null : wrapEntry(entry);
    }

    @Override
    @CheckForNull
    public K lowerKey(@ParametricNullness K key) {
      return sortedMap().lowerKey(key);
    }

    @Override
    @CheckForNull
    public Entry<K, Collection<V>> floorEntry(@ParametricNullness K key) {
      Entry<K, Collection<V>> entry = sortedMap().floorEntry(key);
      return (entry == null) ? null : wrapEntry(entry);
    }

    @Override
    @CheckForNull
    public K floorKey(@ParametricNullness K key) {
      return sortedMap().floorKey(key);
    }

    @Override
    @CheckForNull
    public Entry<K, Collection<V>> ceilingEntry(@ParametricNullness K key) {
      Entry<K, Collection<V>> entry = sortedMap().ceilingEntry(key);
      return (entry == null) ? null : wrapEntry(entry);
    }

    @Override
    @CheckForNull
    public K ceilingKey(@ParametricNullness K key) {
      return sortedMap().ceilingKey(key);
    }

    @Override
    @CheckForNull
    public Entry<K, Collection<V>> higherEntry(@ParametricNullness K key) {
      Entry<K, Collection<V>> entry = sortedMap().higherEntry(key);
      return (entry == null) ? null : wrapEntry(entry);
    }

    @Override
    @CheckForNull
    public K higherKey(@ParametricNullness K key) {
      return sortedMap().higherKey(key);
    }

    @Override
    @CheckForNull
    public Entry<K, Collection<V>> firstEntry() {
      Entry<K, Collection<V>> entry = sortedMap().firstEntry();
      return (entry == null) ? null : wrapEntry(entry);
    }

    @Override
    @CheckForNull
    public Entry<K, Collection<V>> lastEntry() {
      Entry<K, Collection<V>> entry = sortedMap().lastEntry();
      return (entry == null) ? null : wrapEntry(entry);
    }

    @Override
    @CheckForNull
    public Entry<K, Collection<V>> pollFirstEntry() {
      return pollAsMapEntry(entrySet().iterator());
    }

    @Override
    @CheckForNull
    public Entry<K, Collection<V>> pollLastEntry() {
      return pollAsMapEntry(descendingMap().entrySet().iterator());
    }

    @CheckForNull
    Entry<K, Collection<V>> pollAsMapEntry(Iterator<Entry<K, Collection<V>>> entryIterator) {
      if (!entryIterator.hasNext()) {
        return null;
      }
      Entry<K, Collection<V>> entry = entryIterator.next();
      Collection<V> output = createCollection();
      output.addAll(entry.getValue());
      entryIterator.remove();
      return Maps.immutableEntry(entry.getKey(), unmodifiableCollectionSubclass(output));
    }

    @Override
    public NavigableMap<K, Collection<V>> descendingMap() {
      return new NavigableAsMap(sortedMap().descendingMap());
    }

    @Override
    public NavigableSet<K> keySet() {
      return (NavigableSet<K>) super.keySet();
    }

    @Override
    NavigableSet<K> createKeySet() {
      return new NavigableKeySet(sortedMap());
    }

    @Override
    public NavigableSet<K> navigableKeySet() {
      return keySet();
    }

    @Override
    public NavigableSet<K> descendingKeySet() {
      return descendingMap().navigableKeySet();
    }

    @Override
    public NavigableMap<K, Collection<V>> subMap(
        @ParametricNullness K fromKey, @ParametricNullness K toKey) {
      return subMap(fromKey, true, toKey, false);
    }

    @Override
    public NavigableMap<K, Collection<V>> subMap(
        @ParametricNullness K fromKey,
        boolean fromInclusive,
        @ParametricNullness K toKey,
        boolean toInclusive) {
      return new NavigableAsMap(sortedMap().subMap(fromKey, fromInclusive, toKey, toInclusive));
    }

    @Override
    public NavigableMap<K, Collection<V>> headMap(@ParametricNullness K toKey) {
      return headMap(toKey, false);
    }

    @Override
    public NavigableMap<K, Collection<V>> headMap(@ParametricNullness K toKey, boolean inclusive) {
      return new NavigableAsMap(sortedMap().headMap(toKey, inclusive));
    }

    @Override
    public NavigableMap<K, Collection<V>> tailMap(@ParametricNullness K fromKey) {
      return tailMap(fromKey, true);
    }

    @Override
    public NavigableMap<K, Collection<V>> tailMap(
        @ParametricNullness K fromKey, boolean inclusive) {
      return new NavigableAsMap(sortedMap().tailMap(fromKey, inclusive));
    }
  }

  private static final long serialVersionUID = 2447537837011683357L;
}