001/*
002 * Copyright (C) 2009 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.base.Preconditions.checkNotNull;
021import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
022import static com.google.common.collect.Maps.keyOrNull;
023import static java.util.Objects.requireNonNull;
024
025import com.google.common.annotations.Beta;
026import com.google.common.annotations.GwtCompatible;
027import com.google.common.annotations.GwtIncompatible;
028import com.google.common.annotations.J2ktIncompatible;
029import com.google.errorprone.annotations.CanIgnoreReturnValue;
030import com.google.errorprone.annotations.DoNotCall;
031import java.io.InvalidObjectException;
032import java.io.ObjectInputStream;
033import java.util.AbstractMap;
034import java.util.Arrays;
035import java.util.Comparator;
036import java.util.Map;
037import java.util.NavigableMap;
038import java.util.SortedMap;
039import java.util.TreeMap;
040import java.util.function.BinaryOperator;
041import java.util.function.Function;
042import java.util.stream.Collector;
043import java.util.stream.Collectors;
044import javax.annotation.CheckForNull;
045import org.checkerframework.checker.nullness.qual.Nullable;
046
047/**
048 * A {@link NavigableMap} whose contents will never change, with many other important properties
049 * detailed at {@link ImmutableCollection}.
050 *
051 * <p><b>Warning:</b> as with any sorted collection, you are strongly advised not to use a {@link
052 * Comparator} or {@link Comparable} type whose comparison behavior is <i>inconsistent with
053 * equals</i>. That is, {@code a.compareTo(b)} or {@code comparator.compare(a, b)} should equal zero
054 * <i>if and only if</i> {@code a.equals(b)}. If this advice is not followed, the resulting map will
055 * not correctly obey its specification.
056 *
057 * <p>See the Guava User Guide article on <a href=
058 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>.
059 *
060 * @author Jared Levy
061 * @author Louis Wasserman
062 * @since 2.0 (implements {@code NavigableMap} since 12.0)
063 */
064@GwtCompatible(serializable = true, emulated = true)
065@ElementTypesAreNonnullByDefault
066public final class ImmutableSortedMap<K, V> extends ImmutableMap<K, V>
067    implements NavigableMap<K, V> {
068  /**
069   * Returns a {@link Collector} that accumulates elements into an {@code ImmutableSortedMap} whose
070   * keys and values are the result of applying the provided mapping functions to the input
071   * elements. The generated map is sorted by the specified comparator.
072   *
073   * <p>If the mapped keys contain duplicates (according to the specified comparator), an {@code
074   * IllegalArgumentException} is thrown when the collection operation is performed. (This differs
075   * from the {@code Collector} returned by {@link Collectors#toMap(Function, Function)}, which
076   * throws an {@code IllegalStateException}.)
077   *
078   * @since 33.2.0 (available since 21.0 in guava-jre)
079   */
080  @SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"})
081  @IgnoreJRERequirement // Users will use this only if they're already using streams.
082  @Beta // TODO: b/288085449 - Remove.
083  public static <T extends @Nullable Object, K, V>
084      Collector<T, ?, ImmutableSortedMap<K, V>> toImmutableSortedMap(
085          Comparator<? super K> comparator,
086          Function<? super T, ? extends K> keyFunction,
087          Function<? super T, ? extends V> valueFunction) {
088    return CollectCollectors.toImmutableSortedMap(comparator, keyFunction, valueFunction);
089  }
090
091  /**
092   * Returns a {@link Collector} that accumulates elements into an {@code ImmutableSortedMap} whose
093   * keys and values are the result of applying the provided mapping functions to the input
094   * elements.
095   *
096   * <p>If the mapped keys contain duplicates (according to the comparator), the values are merged
097   * using the specified merging function. Entries will appear in the encounter order of the first
098   * occurrence of the key.
099   *
100   * @since 33.2.0 (available since 21.0 in guava-jre)
101   */
102  @SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"})
103  @IgnoreJRERequirement // Users will use this only if they're already using streams.
104  @Beta // TODO: b/288085449 - Remove.
105  public static <T extends @Nullable Object, K, V>
106      Collector<T, ?, ImmutableSortedMap<K, V>> toImmutableSortedMap(
107          Comparator<? super K> comparator,
108          Function<? super T, ? extends K> keyFunction,
109          Function<? super T, ? extends V> valueFunction,
110          BinaryOperator<V> mergeFunction) {
111    return CollectCollectors.toImmutableSortedMap(
112        comparator, keyFunction, valueFunction, mergeFunction);
113  }
114
115  /*
116   * TODO(kevinb): Confirm that ImmutableSortedMap is faster to construct and
117   * uses less memory than TreeMap; then say so in the class Javadoc.
118   */
119  private static final Comparator<?> NATURAL_ORDER = Ordering.natural();
120
121  private static final ImmutableSortedMap<Comparable<?>, Object> NATURAL_EMPTY_MAP =
122      new ImmutableSortedMap<>(
123          ImmutableSortedSet.emptySet(Ordering.natural()), ImmutableList.<Object>of());
124
125  static <K, V> ImmutableSortedMap<K, V> emptyMap(Comparator<? super K> comparator) {
126    if (Ordering.natural().equals(comparator)) {
127      return of();
128    } else {
129      return new ImmutableSortedMap<>(
130          ImmutableSortedSet.emptySet(comparator), ImmutableList.<V>of());
131    }
132  }
133
134  /**
135   * Returns the empty sorted map.
136   *
137   * <p><b>Performance note:</b> the instance returned is a singleton.
138   */
139  @SuppressWarnings("unchecked")
140  // unsafe, comparator() returns a comparator on the specified type
141  // TODO(kevinb): evaluate whether or not of().comparator() should return null
142  public static <K, V> ImmutableSortedMap<K, V> of() {
143    return (ImmutableSortedMap<K, V>) NATURAL_EMPTY_MAP;
144  }
145
146  /** Returns an immutable map containing a single entry. */
147  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(K k1, V v1) {
148    return of(Ordering.natural(), k1, v1);
149  }
150
151  /** Returns an immutable map containing a single entry. */
152  private static <K, V> ImmutableSortedMap<K, V> of(Comparator<? super K> comparator, K k1, V v1) {
153    return new ImmutableSortedMap<>(
154        new RegularImmutableSortedSet<K>(ImmutableList.of(k1), checkNotNull(comparator)),
155        ImmutableList.of(v1));
156  }
157
158  /**
159   * Returns an immutable sorted map containing the given entries, sorted by the natural ordering of
160   * their keys.
161   *
162   * @throws IllegalArgumentException if the two keys are equal according to their natural ordering
163   */
164  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(
165      K k1, V v1, K k2, V v2) {
166    return fromEntries(entryOf(k1, v1), entryOf(k2, v2));
167  }
168
169  /**
170   * Returns an immutable sorted map containing the given entries, sorted by the natural ordering of
171   * their keys.
172   *
173   * @throws IllegalArgumentException if any two keys are equal according to their natural ordering
174   */
175  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(
176      K k1, V v1, K k2, V v2, K k3, V v3) {
177    return fromEntries(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3));
178  }
179
180  /**
181   * Returns an immutable sorted map containing the given entries, sorted by the natural ordering of
182   * their keys.
183   *
184   * @throws IllegalArgumentException if any two keys are equal according to their natural ordering
185   */
186  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(
187      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
188    return fromEntries(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4));
189  }
190
191  /**
192   * Returns an immutable sorted map containing the given entries, sorted by the natural ordering of
193   * their keys.
194   *
195   * @throws IllegalArgumentException if any two keys are equal according to their natural ordering
196   */
197  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(
198      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
199    return fromEntries(
200        entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5));
201  }
202
203  /**
204   * Returns an immutable sorted map containing the given entries, sorted by the natural ordering of
205   * their keys.
206   *
207   * @throws IllegalArgumentException if any two keys are equal according to their natural ordering
208   * @since 31.0
209   */
210  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(
211      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) {
212    return fromEntries(
213        entryOf(k1, v1),
214        entryOf(k2, v2),
215        entryOf(k3, v3),
216        entryOf(k4, v4),
217        entryOf(k5, v5),
218        entryOf(k6, v6));
219  }
220
221  /**
222   * Returns an immutable sorted map containing the given entries, sorted by the natural ordering of
223   * their keys.
224   *
225   * @throws IllegalArgumentException if any two keys are equal according to their natural ordering
226   * @since 31.0
227   */
228  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(
229      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) {
230    return fromEntries(
231        entryOf(k1, v1),
232        entryOf(k2, v2),
233        entryOf(k3, v3),
234        entryOf(k4, v4),
235        entryOf(k5, v5),
236        entryOf(k6, v6),
237        entryOf(k7, v7));
238  }
239
240  /**
241   * Returns an immutable sorted map containing the given entries, sorted by the natural ordering of
242   * their keys.
243   *
244   * @throws IllegalArgumentException if any two keys are equal according to their natural ordering
245   * @since 31.0
246   */
247  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(
248      K k1,
249      V v1,
250      K k2,
251      V v2,
252      K k3,
253      V v3,
254      K k4,
255      V v4,
256      K k5,
257      V v5,
258      K k6,
259      V v6,
260      K k7,
261      V v7,
262      K k8,
263      V v8) {
264    return fromEntries(
265        entryOf(k1, v1),
266        entryOf(k2, v2),
267        entryOf(k3, v3),
268        entryOf(k4, v4),
269        entryOf(k5, v5),
270        entryOf(k6, v6),
271        entryOf(k7, v7),
272        entryOf(k8, v8));
273  }
274
275  /**
276   * Returns an immutable sorted map containing the given entries, sorted by the natural ordering of
277   * their keys.
278   *
279   * @throws IllegalArgumentException if any two keys are equal according to their natural ordering
280   * @since 31.0
281   */
282  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(
283      K k1,
284      V v1,
285      K k2,
286      V v2,
287      K k3,
288      V v3,
289      K k4,
290      V v4,
291      K k5,
292      V v5,
293      K k6,
294      V v6,
295      K k7,
296      V v7,
297      K k8,
298      V v8,
299      K k9,
300      V v9) {
301    return fromEntries(
302        entryOf(k1, v1),
303        entryOf(k2, v2),
304        entryOf(k3, v3),
305        entryOf(k4, v4),
306        entryOf(k5, v5),
307        entryOf(k6, v6),
308        entryOf(k7, v7),
309        entryOf(k8, v8),
310        entryOf(k9, v9));
311  }
312
313  /**
314   * Returns an immutable sorted map containing the given entries, sorted by the natural ordering of
315   * their keys.
316   *
317   * @throws IllegalArgumentException if any two keys are equal according to their natural ordering
318   * @since 31.0
319   */
320  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(
321      K k1,
322      V v1,
323      K k2,
324      V v2,
325      K k3,
326      V v3,
327      K k4,
328      V v4,
329      K k5,
330      V v5,
331      K k6,
332      V v6,
333      K k7,
334      V v7,
335      K k8,
336      V v8,
337      K k9,
338      V v9,
339      K k10,
340      V v10) {
341    return fromEntries(
342        entryOf(k1, v1),
343        entryOf(k2, v2),
344        entryOf(k3, v3),
345        entryOf(k4, v4),
346        entryOf(k5, v5),
347        entryOf(k6, v6),
348        entryOf(k7, v7),
349        entryOf(k8, v8),
350        entryOf(k9, v9),
351        entryOf(k10, v10));
352  }
353
354  /**
355   * Returns an immutable map containing the same entries as {@code map}, sorted by the natural
356   * ordering of the keys.
357   *
358   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
359   * safe to do so. The exact circumstances under which a copy will or will not be performed are
360   * undocumented and subject to change.
361   *
362   * <p>This method is not type-safe, as it may be called on a map with keys that are not mutually
363   * comparable.
364   *
365   * @throws ClassCastException if the keys in {@code map} are not mutually comparable
366   * @throws NullPointerException if any key or value in {@code map} is null
367   * @throws IllegalArgumentException if any two keys are equal according to their natural ordering
368   */
369  public static <K, V> ImmutableSortedMap<K, V> copyOf(Map<? extends K, ? extends V> map) {
370    // Hack around K not being a subtype of Comparable.
371    // Unsafe, see ImmutableSortedSetFauxverideShim.
372    @SuppressWarnings("unchecked")
373    Ordering<K> naturalOrder = (Ordering<K>) NATURAL_ORDER;
374    return copyOfInternal(map, naturalOrder);
375  }
376
377  /**
378   * Returns an immutable map containing the same entries as {@code map}, with keys sorted by the
379   * provided comparator.
380   *
381   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
382   * safe to do so. The exact circumstances under which a copy will or will not be performed are
383   * undocumented and subject to change.
384   *
385   * @throws NullPointerException if any key or value in {@code map} is null
386   * @throws IllegalArgumentException if any two keys are equal according to the comparator
387   */
388  public static <K, V> ImmutableSortedMap<K, V> copyOf(
389      Map<? extends K, ? extends V> map, Comparator<? super K> comparator) {
390    return copyOfInternal(map, checkNotNull(comparator));
391  }
392
393  /**
394   * Returns an immutable map containing the given entries, with keys sorted by their natural
395   * ordering.
396   *
397   * <p>This method is not type-safe, as it may be called on a map with keys that are not mutually
398   * comparable.
399   *
400   * @throws NullPointerException if any key or value in {@code map} is null
401   * @throws IllegalArgumentException if any two keys are equal according to the comparator
402   * @since 19.0
403   */
404  public static <K, V> ImmutableSortedMap<K, V> copyOf(
405      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
406    // Hack around K not being a subtype of Comparable.
407    // Unsafe, see ImmutableSortedSetFauxverideShim.
408    @SuppressWarnings("unchecked")
409    Ordering<K> naturalOrder = (Ordering<K>) NATURAL_ORDER;
410    return copyOf(entries, naturalOrder);
411  }
412
413  /**
414   * Returns an immutable map containing the given entries, with keys sorted by the provided
415   * comparator.
416   *
417   * @throws NullPointerException if any key or value in {@code map} is null
418   * @throws IllegalArgumentException if any two keys are equal according to the comparator
419   * @since 19.0
420   */
421  public static <K, V> ImmutableSortedMap<K, V> copyOf(
422      Iterable<? extends Entry<? extends K, ? extends V>> entries,
423      Comparator<? super K> comparator) {
424    return fromEntries(checkNotNull(comparator), false, entries);
425  }
426
427  /**
428   * Returns an immutable map containing the same entries as the provided sorted map, with the same
429   * ordering.
430   *
431   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
432   * safe to do so. The exact circumstances under which a copy will or will not be performed are
433   * undocumented and subject to change.
434   *
435   * @throws NullPointerException if any key or value in {@code map} is null
436   */
437  @SuppressWarnings("unchecked")
438  public static <K, V> ImmutableSortedMap<K, V> copyOfSorted(SortedMap<K, ? extends V> map) {
439    Comparator<? super K> comparator = map.comparator();
440    if (comparator == null) {
441      // If map has a null comparator, the keys should have a natural ordering,
442      // even though K doesn't explicitly implement Comparable.
443      comparator = (Comparator<? super K>) NATURAL_ORDER;
444    }
445    if (map instanceof ImmutableSortedMap) {
446      // TODO(kevinb): Prove that this cast is safe, even though
447      // Collections.unmodifiableSortedMap requires the same key type.
448      @SuppressWarnings("unchecked")
449      ImmutableSortedMap<K, V> kvMap = (ImmutableSortedMap<K, V>) map;
450      if (!kvMap.isPartialView()) {
451        return kvMap;
452      }
453    }
454    return fromEntries(comparator, true, map.entrySet());
455  }
456
457  private static <K, V> ImmutableSortedMap<K, V> copyOfInternal(
458      Map<? extends K, ? extends V> map, Comparator<? super K> comparator) {
459    boolean sameComparator = false;
460    if (map instanceof SortedMap) {
461      SortedMap<?, ?> sortedMap = (SortedMap<?, ?>) map;
462      Comparator<?> comparator2 = sortedMap.comparator();
463      sameComparator =
464          (comparator2 == null) ? comparator == NATURAL_ORDER : comparator.equals(comparator2);
465    }
466
467    if (sameComparator && (map instanceof ImmutableSortedMap)) {
468      // TODO(kevinb): Prove that this cast is safe, even though
469      // Collections.unmodifiableSortedMap requires the same key type.
470      @SuppressWarnings("unchecked")
471      ImmutableSortedMap<K, V> kvMap = (ImmutableSortedMap<K, V>) map;
472      if (!kvMap.isPartialView()) {
473        return kvMap;
474      }
475    }
476    return fromEntries(comparator, sameComparator, map.entrySet());
477  }
478
479  private static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> fromEntries(
480      Entry<K, V>... entries) {
481    return fromEntries(Ordering.natural(), false, entries, entries.length);
482  }
483
484  /**
485   * Accepts a collection of possibly-null entries. If {@code sameComparator}, then it is assumed
486   * that they do not need to be sorted or checked for dupes.
487   */
488  private static <K, V> ImmutableSortedMap<K, V> fromEntries(
489      Comparator<? super K> comparator,
490      boolean sameComparator,
491      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
492    // "adding" type params to an array of a raw type should be safe as
493    // long as no one can ever cast that same array instance back to a
494    // raw type.
495    @SuppressWarnings("unchecked")
496    Entry<K, V>[] entryArray = (Entry[]) Iterables.toArray(entries, EMPTY_ENTRY_ARRAY);
497    return fromEntries(comparator, sameComparator, entryArray, entryArray.length);
498  }
499
500  @SuppressWarnings("nullness") // TODO: b/316358623 - Remove after checker fix.
501  private static <K, V> ImmutableSortedMap<K, V> fromEntries(
502      final Comparator<? super K> comparator,
503      boolean sameComparator,
504      @Nullable Entry<K, V>[] entryArray,
505      int size) {
506    switch (size) {
507      case 0:
508        return emptyMap(comparator);
509      case 1:
510        // requireNonNull is safe because the first `size` elements have been filled in.
511        Entry<K, V> onlyEntry = requireNonNull(entryArray[0]);
512        return of(comparator, onlyEntry.getKey(), onlyEntry.getValue());
513      default:
514        Object[] keys = new Object[size];
515        Object[] values = new Object[size];
516        if (sameComparator) {
517          // Need to check for nulls, but don't need to sort or validate.
518          for (int i = 0; i < size; i++) {
519            // requireNonNull is safe because the first `size` elements have been filled in.
520            Entry<K, V> entry = requireNonNull(entryArray[i]);
521            Object key = entry.getKey();
522            Object value = entry.getValue();
523            checkEntryNotNull(key, value);
524            keys[i] = key;
525            values[i] = value;
526          }
527        } else {
528          // Need to sort and check for nulls and dupes.
529          // Inline the Comparator implementation rather than transforming with a Function
530          // to save code size.
531          Arrays.sort(
532              entryArray,
533              0,
534              size,
535              (e1, e2) -> {
536                // requireNonNull is safe because the first `size` elements have been filled in.
537                requireNonNull(e1);
538                requireNonNull(e2);
539                return comparator.compare(e1.getKey(), e2.getKey());
540              });
541          // requireNonNull is safe because the first `size` elements have been filled in.
542          Entry<K, V> firstEntry = requireNonNull(entryArray[0]);
543          K prevKey = firstEntry.getKey();
544          keys[0] = prevKey;
545          values[0] = firstEntry.getValue();
546          checkEntryNotNull(keys[0], values[0]);
547          for (int i = 1; i < size; i++) {
548            // requireNonNull is safe because the first `size` elements have been filled in.
549            Entry<K, V> prevEntry = requireNonNull(entryArray[i - 1]);
550            Entry<K, V> entry = requireNonNull(entryArray[i]);
551            K key = entry.getKey();
552            V value = entry.getValue();
553            checkEntryNotNull(key, value);
554            keys[i] = key;
555            values[i] = value;
556            checkNoConflict(comparator.compare(prevKey, key) != 0, "key", prevEntry, entry);
557            prevKey = key;
558          }
559        }
560        return new ImmutableSortedMap<>(
561            new RegularImmutableSortedSet<K>(ImmutableList.<K>asImmutableList(keys), comparator),
562            ImmutableList.<V>asImmutableList(values));
563    }
564  }
565
566  /**
567   * Returns a builder that creates immutable sorted maps whose keys are ordered by their natural
568   * ordering. The sorted maps use {@link Ordering#natural()} as the comparator.
569   */
570  public static <K extends Comparable<?>, V> Builder<K, V> naturalOrder() {
571    return new Builder<>(Ordering.natural());
572  }
573
574  /**
575   * Returns a builder that creates immutable sorted maps with an explicit comparator. If the
576   * comparator has a more general type than the map's keys, such as creating a {@code
577   * SortedMap<Integer, String>} with a {@code Comparator<Number>}, use the {@link Builder}
578   * constructor instead.
579   *
580   * @throws NullPointerException if {@code comparator} is null
581   */
582  public static <K, V> Builder<K, V> orderedBy(Comparator<K> comparator) {
583    return new Builder<>(comparator);
584  }
585
586  /**
587   * Returns a builder that creates immutable sorted maps whose keys are ordered by the reverse of
588   * their natural ordering.
589   */
590  public static <K extends Comparable<?>, V> Builder<K, V> reverseOrder() {
591    return new Builder<>(Ordering.<K>natural().reverse());
592  }
593
594  /**
595   * A builder for creating immutable sorted map instances, especially {@code public static final}
596   * maps ("constant maps"). Example:
597   *
598   * <pre>{@code
599   * static final ImmutableSortedMap<Integer, String> INT_TO_WORD =
600   *     new ImmutableSortedMap.Builder<Integer, String>(Ordering.natural())
601   *         .put(1, "one")
602   *         .put(2, "two")
603   *         .put(3, "three")
604   *         .buildOrThrow();
605   * }</pre>
606   *
607   * <p>For <i>small</i> immutable sorted maps, the {@code ImmutableSortedMap.of()} methods are even
608   * more convenient.
609   *
610   * <p>Builder instances can be reused - it is safe to call {@link #buildOrThrow} multiple times to
611   * build multiple maps in series. Each map is a superset of the maps created before it.
612   *
613   * @since 2.0
614   */
615  public static class Builder<K, V> extends ImmutableMap.Builder<K, V> {
616    private transient @Nullable Object[] keys;
617    private transient @Nullable Object[] values;
618    private final Comparator<? super K> comparator;
619
620    /**
621     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
622     * ImmutableSortedMap#orderedBy}.
623     */
624    public Builder(Comparator<? super K> comparator) {
625      this(comparator, ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY);
626    }
627
628    private Builder(Comparator<? super K> comparator, int initialCapacity) {
629      this.comparator = checkNotNull(comparator);
630      this.keys = new @Nullable Object[initialCapacity];
631      this.values = new @Nullable Object[initialCapacity];
632    }
633
634    private void ensureCapacity(int minCapacity) {
635      if (minCapacity > keys.length) {
636        int newCapacity = ImmutableCollection.Builder.expandedCapacity(keys.length, minCapacity);
637        this.keys = Arrays.copyOf(keys, newCapacity);
638        this.values = Arrays.copyOf(values, newCapacity);
639      }
640    }
641
642    /**
643     * Associates {@code key} with {@code value} in the built map. Duplicate keys, according to the
644     * comparator (which might be the keys' natural order), are not allowed, and will cause {@link
645     * #build} to fail.
646     */
647    @CanIgnoreReturnValue
648    @Override
649    public Builder<K, V> put(K key, V value) {
650      ensureCapacity(size + 1);
651      checkEntryNotNull(key, value);
652      keys[size] = key;
653      values[size] = value;
654      size++;
655      return this;
656    }
657
658    /**
659     * Adds the given {@code entry} to the map, making it immutable if necessary. Duplicate keys,
660     * according to the comparator (which might be the keys' natural order), are not allowed, and
661     * will cause {@link #build} to fail.
662     *
663     * @since 11.0
664     */
665    @CanIgnoreReturnValue
666    @Override
667    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
668      super.put(entry);
669      return this;
670    }
671
672    /**
673     * Associates all of the given map's keys and values in the built map. Duplicate keys, according
674     * to the comparator (which might be the keys' natural order), are not allowed, and will cause
675     * {@link #build} to fail.
676     *
677     * @throws NullPointerException if any key or value in {@code map} is null
678     */
679    @CanIgnoreReturnValue
680    @Override
681    public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
682      super.putAll(map);
683      return this;
684    }
685
686    /**
687     * Adds all the given entries to the built map. Duplicate keys, according to the comparator
688     * (which might be the keys' natural order), are not allowed, and will cause {@link #build} to
689     * fail.
690     *
691     * @throws NullPointerException if any key, value, or entry is null
692     * @since 19.0
693     */
694    @CanIgnoreReturnValue
695    @Override
696    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
697      super.putAll(entries);
698      return this;
699    }
700
701    /**
702     * Throws an {@code UnsupportedOperationException}.
703     *
704     * @since 19.0
705     * @deprecated Unsupported by ImmutableSortedMap.Builder.
706     */
707    @CanIgnoreReturnValue
708    @Override
709    @Deprecated
710    @DoNotCall("Always throws UnsupportedOperationException")
711    public final Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
712      throw new UnsupportedOperationException("Not available on ImmutableSortedMap.Builder");
713    }
714
715    @CanIgnoreReturnValue
716    Builder<K, V> combine(ImmutableSortedMap.Builder<K, V> other) {
717      ensureCapacity(size + other.size);
718      System.arraycopy(other.keys, 0, this.keys, this.size, other.size);
719      System.arraycopy(other.values, 0, this.values, this.size, other.size);
720      size += other.size;
721      return this;
722    }
723
724    /**
725     * Returns a newly-created immutable sorted map.
726     *
727     * <p>Prefer the equivalent method {@link #buildOrThrow()} to make it explicit that the method
728     * will throw an exception if there are duplicate keys. The {@code build()} method will soon be
729     * deprecated.
730     *
731     * @throws IllegalArgumentException if any two keys are equal according to the comparator (which
732     *     might be the keys' natural order)
733     */
734    @Override
735    public ImmutableSortedMap<K, V> build() {
736      return buildOrThrow();
737    }
738
739    /**
740     * Returns a newly-created immutable sorted map, or throws an exception if any two keys are
741     * equal.
742     *
743     * @throws IllegalArgumentException if any two keys are equal according to the comparator (which
744     *     might be the keys' natural order)
745     * @since 31.0
746     */
747    @Override
748    @SuppressWarnings("unchecked") // see inline comments
749    public ImmutableSortedMap<K, V> buildOrThrow() {
750      switch (size) {
751        case 0:
752          return emptyMap(comparator);
753        case 1:
754          // We're careful to put only K and V instances in.
755          // requireNonNull is safe because the first `size` elements have been filled in.
756          ImmutableSortedMap<K, V> result =
757              of(comparator, (K) requireNonNull(keys[0]), (V) requireNonNull(values[0]));
758          return result;
759        default:
760          Object[] sortedKeys = Arrays.copyOf(keys, size);
761          // We're careful to put only K instances in.
762          K[] sortedKs = (K[]) sortedKeys;
763          Arrays.sort(sortedKs, comparator);
764          Object[] sortedValues = new Object[size];
765
766          // We might, somehow, be able to reorder values in-place.  But it doesn't seem like
767          // there's a way around creating the separate sortedKeys array, and if we're allocating
768          // one array of size n, we might as well allocate two -- to say nothing of the allocation
769          // done in Arrays.sort.
770          for (int i = 0; i < size; i++) {
771            // We're careful to put only K instances in.
772            if (i > 0 && comparator.compare((K) sortedKeys[i - 1], (K) sortedKeys[i]) == 0) {
773              throw new IllegalArgumentException(
774                  "keys required to be distinct but compared as equal: "
775                      + sortedKeys[i - 1]
776                      + " and "
777                      + sortedKeys[i]);
778            }
779            // requireNonNull is safe because the first `size` elements have been filled in.
780            // We're careful to put only K instances in.
781            int index =
782                Arrays.binarySearch((K[]) sortedKeys, (K) requireNonNull(keys[i]), comparator);
783            sortedValues[index] = requireNonNull(values[i]);
784          }
785          return new ImmutableSortedMap<K, V>(
786              new RegularImmutableSortedSet<K>(
787                  ImmutableList.<K>asImmutableList(sortedKeys), comparator),
788              ImmutableList.<V>asImmutableList(sortedValues));
789      }
790    }
791
792    /**
793     * Throws UnsupportedOperationException. A future version may support this operation. Then the
794     * value for any given key will be the one that was last supplied in a {@code put} operation for
795     * that key.
796     *
797     * @throws UnsupportedOperationException always
798     * @since 31.1
799     * @deprecated This method is not currently implemented, and may never be.
800     */
801    @DoNotCall
802    @Deprecated
803    @Override
804    public final ImmutableSortedMap<K, V> buildKeepingLast() {
805      // TODO(emcmanus): implement
806      throw new UnsupportedOperationException(
807          "ImmutableSortedMap.Builder does not yet implement buildKeepingLast()");
808    }
809  }
810
811  private final transient RegularImmutableSortedSet<K> keySet;
812  private final transient ImmutableList<V> valueList;
813  @CheckForNull private transient ImmutableSortedMap<K, V> descendingMap;
814
815  ImmutableSortedMap(RegularImmutableSortedSet<K> keySet, ImmutableList<V> valueList) {
816    this(keySet, valueList, null);
817  }
818
819  ImmutableSortedMap(
820      RegularImmutableSortedSet<K> keySet,
821      ImmutableList<V> valueList,
822      @CheckForNull ImmutableSortedMap<K, V> descendingMap) {
823    this.keySet = keySet;
824    this.valueList = valueList;
825    this.descendingMap = descendingMap;
826  }
827
828  @Override
829  public int size() {
830    return valueList.size();
831  }
832
833  @Override
834  @CheckForNull
835  public V get(@CheckForNull Object key) {
836    int index = keySet.indexOf(key);
837    return (index == -1) ? null : valueList.get(index);
838  }
839
840  @Override
841  boolean isPartialView() {
842    return keySet.isPartialView() || valueList.isPartialView();
843  }
844
845  /** Returns an immutable set of the mappings in this map, sorted by the key ordering. */
846  @Override
847  public ImmutableSet<Entry<K, V>> entrySet() {
848    return super.entrySet();
849  }
850
851  @Override
852  ImmutableSet<Entry<K, V>> createEntrySet() {
853    class EntrySet extends ImmutableMapEntrySet<K, V> {
854      @Override
855      public UnmodifiableIterator<Entry<K, V>> iterator() {
856        return asList().iterator();
857      }
858
859      @Override
860      ImmutableList<Entry<K, V>> createAsList() {
861        return new ImmutableList<Entry<K, V>>() {
862          @Override
863          public Entry<K, V> get(int index) {
864            return new AbstractMap.SimpleImmutableEntry<>(
865                keySet.asList().get(index), valueList.get(index));
866          }
867
868          @Override
869          boolean isPartialView() {
870            return true;
871          }
872
873          @Override
874          public int size() {
875            return ImmutableSortedMap.this.size();
876          }
877
878          // redeclare to help optimizers with b/310253115
879          @SuppressWarnings("RedundantOverride")
880          @Override
881          @J2ktIncompatible // serialization
882          @GwtIncompatible // serialization
883          Object writeReplace() {
884            return super.writeReplace();
885          }
886        };
887      }
888
889      @Override
890      ImmutableMap<K, V> map() {
891        return ImmutableSortedMap.this;
892      }
893
894      // redeclare to help optimizers with b/310253115
895      @SuppressWarnings("RedundantOverride")
896      @Override
897      @J2ktIncompatible // serialization
898      @GwtIncompatible // serialization
899      Object writeReplace() {
900        return super.writeReplace();
901      }
902    }
903    return isEmpty() ? ImmutableSet.<Entry<K, V>>of() : new EntrySet();
904  }
905
906  /** Returns an immutable sorted set of the keys in this map. */
907  @Override
908  public ImmutableSortedSet<K> keySet() {
909    return keySet;
910  }
911
912  @Override
913  ImmutableSet<K> createKeySet() {
914    throw new AssertionError("should never be called");
915  }
916
917  /**
918   * Returns an immutable collection of the values in this map, sorted by the ordering of the
919   * corresponding keys.
920   */
921  @Override
922  public ImmutableCollection<V> values() {
923    return valueList;
924  }
925
926  @Override
927  ImmutableCollection<V> createValues() {
928    throw new AssertionError("should never be called");
929  }
930
931  /**
932   * Returns the comparator that orders the keys, which is {@link Ordering#natural()} when the
933   * natural ordering of the keys is used. Note that its behavior is not consistent with {@link
934   * TreeMap#comparator()}, which returns {@code null} to indicate natural ordering.
935   */
936  @Override
937  public Comparator<? super K> comparator() {
938    return keySet().comparator();
939  }
940
941  @Override
942  public K firstKey() {
943    return keySet().first();
944  }
945
946  @Override
947  public K lastKey() {
948    return keySet().last();
949  }
950
951  private ImmutableSortedMap<K, V> getSubMap(int fromIndex, int toIndex) {
952    if (fromIndex == 0 && toIndex == size()) {
953      return this;
954    } else if (fromIndex == toIndex) {
955      return emptyMap(comparator());
956    } else {
957      return new ImmutableSortedMap<>(
958          keySet.getSubSet(fromIndex, toIndex), valueList.subList(fromIndex, toIndex));
959    }
960  }
961
962  /**
963   * This method returns a {@code ImmutableSortedMap}, consisting of the entries whose keys are less
964   * than {@code toKey}.
965   *
966   * <p>The {@link SortedMap#headMap} documentation states that a submap of a submap throws an
967   * {@link IllegalArgumentException} if passed a {@code toKey} greater than an earlier {@code
968   * toKey}. However, this method doesn't throw an exception in that situation, but instead keeps
969   * the original {@code toKey}.
970   */
971  @Override
972  public ImmutableSortedMap<K, V> headMap(K toKey) {
973    return headMap(toKey, false);
974  }
975
976  /**
977   * This method returns a {@code ImmutableSortedMap}, consisting of the entries whose keys are less
978   * than (or equal to, if {@code inclusive}) {@code toKey}.
979   *
980   * <p>The {@link SortedMap#headMap} documentation states that a submap of a submap throws an
981   * {@link IllegalArgumentException} if passed a {@code toKey} greater than an earlier {@code
982   * toKey}. However, this method doesn't throw an exception in that situation, but instead keeps
983   * the original {@code toKey}.
984   *
985   * @since 12.0
986   */
987  @Override
988  public ImmutableSortedMap<K, V> headMap(K toKey, boolean inclusive) {
989    return getSubMap(0, keySet.headIndex(checkNotNull(toKey), inclusive));
990  }
991
992  /**
993   * This method returns a {@code ImmutableSortedMap}, consisting of the entries whose keys ranges
994   * from {@code fromKey}, inclusive, to {@code toKey}, exclusive.
995   *
996   * <p>The {@link SortedMap#subMap} documentation states that a submap of a submap throws an {@link
997   * IllegalArgumentException} if passed a {@code fromKey} less than an earlier {@code fromKey}.
998   * However, this method doesn't throw an exception in that situation, but instead keeps the
999   * original {@code fromKey}. Similarly, this method keeps the original {@code toKey}, instead of
1000   * throwing an exception, if passed a {@code toKey} greater than an earlier {@code toKey}.
1001   */
1002  @Override
1003  public ImmutableSortedMap<K, V> subMap(K fromKey, K toKey) {
1004    return subMap(fromKey, true, toKey, false);
1005  }
1006
1007  /**
1008   * This method returns a {@code ImmutableSortedMap}, consisting of the entries whose keys ranges
1009   * from {@code fromKey} to {@code toKey}, inclusive or exclusive as indicated by the boolean
1010   * flags.
1011   *
1012   * <p>The {@link SortedMap#subMap} documentation states that a submap of a submap throws an {@link
1013   * IllegalArgumentException} if passed a {@code fromKey} less than an earlier {@code fromKey}.
1014   * However, this method doesn't throw an exception in that situation, but instead keeps the
1015   * original {@code fromKey}. Similarly, this method keeps the original {@code toKey}, instead of
1016   * throwing an exception, if passed a {@code toKey} greater than an earlier {@code toKey}.
1017   *
1018   * @since 12.0
1019   */
1020  @Override
1021  public ImmutableSortedMap<K, V> subMap(
1022      K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
1023    checkNotNull(fromKey);
1024    checkNotNull(toKey);
1025    checkArgument(
1026        comparator().compare(fromKey, toKey) <= 0,
1027        "expected fromKey <= toKey but %s > %s",
1028        fromKey,
1029        toKey);
1030    return headMap(toKey, toInclusive).tailMap(fromKey, fromInclusive);
1031  }
1032
1033  /**
1034   * This method returns a {@code ImmutableSortedMap}, consisting of the entries whose keys are
1035   * greater than or equals to {@code fromKey}.
1036   *
1037   * <p>The {@link SortedMap#tailMap} documentation states that a submap of a submap throws an
1038   * {@link IllegalArgumentException} if passed a {@code fromKey} less than an earlier {@code
1039   * fromKey}. However, this method doesn't throw an exception in that situation, but instead keeps
1040   * the original {@code fromKey}.
1041   */
1042  @Override
1043  public ImmutableSortedMap<K, V> tailMap(K fromKey) {
1044    return tailMap(fromKey, true);
1045  }
1046
1047  /**
1048   * This method returns a {@code ImmutableSortedMap}, consisting of the entries whose keys are
1049   * greater than (or equal to, if {@code inclusive}) {@code fromKey}.
1050   *
1051   * <p>The {@link SortedMap#tailMap} documentation states that a submap of a submap throws an
1052   * {@link IllegalArgumentException} if passed a {@code fromKey} less than an earlier {@code
1053   * fromKey}. However, this method doesn't throw an exception in that situation, but instead keeps
1054   * the original {@code fromKey}.
1055   *
1056   * @since 12.0
1057   */
1058  @Override
1059  public ImmutableSortedMap<K, V> tailMap(K fromKey, boolean inclusive) {
1060    return getSubMap(keySet.tailIndex(checkNotNull(fromKey), inclusive), size());
1061  }
1062
1063  @Override
1064  @CheckForNull
1065  public Entry<K, V> lowerEntry(K key) {
1066    return headMap(key, false).lastEntry();
1067  }
1068
1069  @Override
1070  @CheckForNull
1071  public K lowerKey(K key) {
1072    return keyOrNull(lowerEntry(key));
1073  }
1074
1075  @Override
1076  @CheckForNull
1077  public Entry<K, V> floorEntry(K key) {
1078    return headMap(key, true).lastEntry();
1079  }
1080
1081  @Override
1082  @CheckForNull
1083  public K floorKey(K key) {
1084    return keyOrNull(floorEntry(key));
1085  }
1086
1087  @Override
1088  @CheckForNull
1089  public Entry<K, V> ceilingEntry(K key) {
1090    return tailMap(key, true).firstEntry();
1091  }
1092
1093  @Override
1094  @CheckForNull
1095  public K ceilingKey(K key) {
1096    return keyOrNull(ceilingEntry(key));
1097  }
1098
1099  @Override
1100  @CheckForNull
1101  public Entry<K, V> higherEntry(K key) {
1102    return tailMap(key, false).firstEntry();
1103  }
1104
1105  @Override
1106  @CheckForNull
1107  public K higherKey(K key) {
1108    return keyOrNull(higherEntry(key));
1109  }
1110
1111  @Override
1112  @CheckForNull
1113  public Entry<K, V> firstEntry() {
1114    return isEmpty() ? null : entrySet().asList().get(0);
1115  }
1116
1117  @Override
1118  @CheckForNull
1119  public Entry<K, V> lastEntry() {
1120    return isEmpty() ? null : entrySet().asList().get(size() - 1);
1121  }
1122
1123  /**
1124   * Guaranteed to throw an exception and leave the map unmodified.
1125   *
1126   * @throws UnsupportedOperationException always
1127   * @deprecated Unsupported operation.
1128   */
1129  @CanIgnoreReturnValue
1130  @Deprecated
1131  @Override
1132  @DoNotCall("Always throws UnsupportedOperationException")
1133  @CheckForNull
1134  public final Entry<K, V> pollFirstEntry() {
1135    throw new UnsupportedOperationException();
1136  }
1137
1138  /**
1139   * Guaranteed to throw an exception and leave the map unmodified.
1140   *
1141   * @throws UnsupportedOperationException always
1142   * @deprecated Unsupported operation.
1143   */
1144  @CanIgnoreReturnValue
1145  @Deprecated
1146  @Override
1147  @DoNotCall("Always throws UnsupportedOperationException")
1148  @CheckForNull
1149  public final Entry<K, V> pollLastEntry() {
1150    throw new UnsupportedOperationException();
1151  }
1152
1153  @Override
1154  public ImmutableSortedMap<K, V> descendingMap() {
1155    // TODO(kevinb): The descendingMap is never actually cached at all. Either:
1156    //
1157    // - Cache it, and annotate the field with @LazyInit.
1158    // - Simplify the code below, and consider eliminating the field (b/287198172), which is also
1159    //   set by one of the constructors.
1160    ImmutableSortedMap<K, V> result = descendingMap;
1161    if (result == null) {
1162      if (isEmpty()) {
1163        return emptyMap(Ordering.from(comparator()).reverse());
1164      } else {
1165        return new ImmutableSortedMap<>(
1166            (RegularImmutableSortedSet<K>) keySet.descendingSet(), valueList.reverse(), this);
1167      }
1168    }
1169    return result;
1170  }
1171
1172  @Override
1173  public ImmutableSortedSet<K> navigableKeySet() {
1174    return keySet;
1175  }
1176
1177  @Override
1178  public ImmutableSortedSet<K> descendingKeySet() {
1179    return keySet.descendingSet();
1180  }
1181
1182  /**
1183   * Serialized type for all ImmutableSortedMap instances. It captures the logical contents and they
1184   * are reconstructed using public factory methods. This ensures that the implementation types
1185   * remain as implementation details.
1186   */
1187  @J2ktIncompatible // serialization
1188  private static class SerializedForm<K, V> extends ImmutableMap.SerializedForm<K, V> {
1189    private final Comparator<? super K> comparator;
1190
1191    SerializedForm(ImmutableSortedMap<K, V> sortedMap) {
1192      super(sortedMap);
1193      comparator = sortedMap.comparator();
1194    }
1195
1196    @Override
1197    Builder<K, V> makeBuilder(int size) {
1198      return new Builder<>(comparator);
1199    }
1200
1201    private static final long serialVersionUID = 0;
1202  }
1203
1204  @Override
1205  @J2ktIncompatible // serialization
1206  Object writeReplace() {
1207    return new SerializedForm<>(this);
1208  }
1209
1210  @J2ktIncompatible // java.io.ObjectInputStream
1211  private void readObject(ObjectInputStream stream) throws InvalidObjectException {
1212    throw new InvalidObjectException("Use SerializedForm");
1213  }
1214
1215  // This class is never actually serialized directly, but we have to make the
1216  // warning go away (and suppressing would suppress for all nested classes too)
1217  private static final long serialVersionUID = 0;
1218
1219  /**
1220   * Not supported. Use {@link #toImmutableSortedMap}, which offers better type-safety, instead.
1221   * This method exists only to hide {@link ImmutableMap#toImmutableMap} from consumers of {@code
1222   * ImmutableSortedMap}.
1223   *
1224   * @throws UnsupportedOperationException always
1225   * @deprecated Use {@link ImmutableSortedMap#toImmutableSortedMap}.
1226   * @since 33.2.0 (available since 21.0 in guava-jre)
1227   */
1228  @DoNotCall("Use toImmutableSortedMap")
1229  @Deprecated
1230  @SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"})
1231  @IgnoreJRERequirement // Users will use this only if they're already using streams.
1232  @Beta // TODO: b/288085449 - Remove.
1233  public static <T extends @Nullable Object, K, V>
1234      Collector<T, ?, ImmutableMap<K, V>> toImmutableMap(
1235          Function<? super T, ? extends K> keyFunction,
1236          Function<? super T, ? extends V> valueFunction) {
1237    throw new UnsupportedOperationException();
1238  }
1239
1240  /**
1241   * Not supported. Use {@link #toImmutableSortedMap}, which offers better type-safety, instead.
1242   * This method exists only to hide {@link ImmutableMap#toImmutableMap} from consumers of {@code
1243   * ImmutableSortedMap}.
1244   *
1245   * @throws UnsupportedOperationException always
1246   * @deprecated Use {@link ImmutableSortedMap#toImmutableSortedMap}.
1247   * @since 33.2.0 (available since 21.0 in guava-jre)
1248   */
1249  @DoNotCall("Use toImmutableSortedMap")
1250  @Deprecated
1251  @SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"})
1252  @IgnoreJRERequirement // Users will use this only if they're already using streams.
1253  @Beta // TODO: b/288085449 - Remove.
1254  public static <T extends @Nullable Object, K, V>
1255      Collector<T, ?, ImmutableMap<K, V>> toImmutableMap(
1256          Function<? super T, ? extends K> keyFunction,
1257          Function<? super T, ? extends V> valueFunction,
1258          BinaryOperator<V> mergeFunction) {
1259    throw new UnsupportedOperationException();
1260  }
1261
1262  /**
1263   * Not supported. Use {@link #naturalOrder}, which offers better type-safety, instead. This method
1264   * exists only to hide {@link ImmutableMap#builder} from consumers of {@code ImmutableSortedMap}.
1265   *
1266   * @throws UnsupportedOperationException always
1267   * @deprecated Use {@link ImmutableSortedMap#naturalOrder}, which offers better type-safety.
1268   */
1269  @DoNotCall("Use naturalOrder")
1270  @Deprecated
1271  public static <K, V> ImmutableSortedMap.Builder<K, V> builder() {
1272    throw new UnsupportedOperationException();
1273  }
1274
1275  /**
1276   * Not supported for ImmutableSortedMap.
1277   *
1278   * @throws UnsupportedOperationException always
1279   * @deprecated Not supported for ImmutableSortedMap.
1280   */
1281  @DoNotCall("Use naturalOrder (which does not accept an expected size)")
1282  @Deprecated
1283  public static <K, V> ImmutableSortedMap.Builder<K, V> builderWithExpectedSize(int expectedSize) {
1284    throw new UnsupportedOperationException();
1285  }
1286
1287  /**
1288   * Not supported. <b>You are attempting to create a map that may contain a non-{@code Comparable}
1289   * key.</b> Proper calls will resolve to the version in {@code ImmutableSortedMap}, not this dummy
1290   * version.
1291   *
1292   * @throws UnsupportedOperationException always
1293   * @deprecated <b>Pass a key of type {@code Comparable} to use {@link
1294   *     ImmutableSortedMap#of(Comparable, Object)}.</b>
1295   */
1296  @DoNotCall("Pass a key of type Comparable")
1297  @Deprecated
1298  public static <K, V> ImmutableSortedMap<K, V> of(K k1, V v1) {
1299    throw new UnsupportedOperationException();
1300  }
1301
1302  /**
1303   * Not supported. <b>You are attempting to create a map that may contain non-{@code Comparable}
1304   * keys.</b> Proper calls will resolve to the version in {@code ImmutableSortedMap}, not this
1305   * dummy version.
1306   *
1307   * @throws UnsupportedOperationException always
1308   * @deprecated <b>Pass keys of type {@code Comparable} to use {@link
1309   *     ImmutableSortedMap#of(Comparable, Object, Comparable, Object)}.</b>
1310   */
1311  @DoNotCall("Pass keys of type Comparable")
1312  @Deprecated
1313  public static <K, V> ImmutableSortedMap<K, V> of(K k1, V v1, K k2, V v2) {
1314    throw new UnsupportedOperationException();
1315  }
1316
1317  /**
1318   * Not supported. <b>You are attempting to create a map that may contain non-{@code Comparable}
1319   * keys.</b> Proper calls to will resolve to the version in {@code ImmutableSortedMap}, not this
1320   * dummy version.
1321   *
1322   * @throws UnsupportedOperationException always
1323   * @deprecated <b>Pass keys of type {@code Comparable} to use {@link
1324   *     ImmutableSortedMap#of(Comparable, Object, Comparable, Object, Comparable, Object)}.</b>
1325   */
1326  @DoNotCall("Pass keys of type Comparable")
1327  @Deprecated
1328  public static <K, V> ImmutableSortedMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
1329    throw new UnsupportedOperationException();
1330  }
1331
1332  /**
1333   * Not supported. <b>You are attempting to create a map that may contain non-{@code Comparable}
1334   * keys.</b> Proper calls will resolve to the version in {@code ImmutableSortedMap}, not this
1335   * dummy version.
1336   *
1337   * @throws UnsupportedOperationException always
1338   * @deprecated <b>Pass keys of type {@code Comparable} to use {@link
1339   *     ImmutableSortedMap#of(Comparable, Object, Comparable, Object, Comparable, Object,
1340   *     Comparable, Object)}.</b>
1341   */
1342  @DoNotCall("Pass keys of type Comparable")
1343  @Deprecated
1344  public static <K, V> ImmutableSortedMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
1345    throw new UnsupportedOperationException();
1346  }
1347
1348  /**
1349   * Not supported. <b>You are attempting to create a map that may contain non-{@code Comparable}
1350   * keys.</b> Proper calls will resolve to the version in {@code ImmutableSortedMap}, not this
1351   * dummy version.
1352   *
1353   * @throws UnsupportedOperationException always
1354   * @deprecated <b>Pass keys of type {@code Comparable} to use {@link
1355   *     ImmutableSortedMap#of(Comparable, Object, Comparable, Object, Comparable, Object,
1356   *     Comparable, Object, Comparable, Object)}.</b>
1357   */
1358  @DoNotCall("Pass keys of type Comparable")
1359  @Deprecated
1360  public static <K, V> ImmutableSortedMap<K, V> of(
1361      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
1362    throw new UnsupportedOperationException();
1363  }
1364
1365  /**
1366   * Not supported. <b>You are attempting to create a map that may contain non-{@code Comparable}
1367   * keys.</b> Proper calls will resolve to the version in {@code ImmutableSortedMap}, not this
1368   * dummy version.
1369   *
1370   * @throws UnsupportedOperationException always
1371   * @deprecated <b>Pass keys of type {@code Comparable} to use {@link
1372   *     ImmutableSortedMap#of(Comparable, Object, Comparable, Object, Comparable, Object,
1373   *     Comparable, Object, Comparable, Object)}.</b>
1374   */
1375  @DoNotCall("Pass keys of type Comparable")
1376  @Deprecated
1377  public static <K, V> ImmutableSortedMap<K, V> of(
1378      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) {
1379    throw new UnsupportedOperationException();
1380  }
1381
1382  /**
1383   * Not supported. <b>You are attempting to create a map that may contain non-{@code Comparable}
1384   * keys.</b> Proper calls will resolve to the version in {@code ImmutableSortedMap}, not this
1385   * dummy version.
1386   *
1387   * @throws UnsupportedOperationException always
1388   * @deprecated <b>Pass keys of type {@code Comparable} to use {@link
1389   *     ImmutableSortedMap#of(Comparable, Object, Comparable, Object, Comparable, Object,
1390   *     Comparable, Object, Comparable, Object)}.</b>
1391   */
1392  @DoNotCall("Pass keys of type Comparable")
1393  @Deprecated
1394  public static <K, V> ImmutableSortedMap<K, V> of(
1395      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) {
1396    throw new UnsupportedOperationException();
1397  }
1398
1399  /**
1400   * Not supported. <b>You are attempting to create a map that may contain non-{@code Comparable}
1401   * keys.</b> Proper calls will resolve to the version in {@code ImmutableSortedMap}, not this
1402   * dummy version.
1403   *
1404   * @throws UnsupportedOperationException always
1405   * @deprecated <b>Pass keys of type {@code Comparable} to use {@link
1406   *     ImmutableSortedMap#of(Comparable, Object, Comparable, Object, Comparable, Object,
1407   *     Comparable, Object, Comparable, Object)}.</b>
1408   */
1409  @DoNotCall("Pass keys of type Comparable")
1410  @Deprecated
1411  public static <K, V> ImmutableSortedMap<K, V> of(
1412      K k1,
1413      V v1,
1414      K k2,
1415      V v2,
1416      K k3,
1417      V v3,
1418      K k4,
1419      V v4,
1420      K k5,
1421      V v5,
1422      K k6,
1423      V v6,
1424      K k7,
1425      V v7,
1426      K k8,
1427      V v8) {
1428    throw new UnsupportedOperationException();
1429  }
1430
1431  /**
1432   * Not supported. <b>You are attempting to create a map that may contain non-{@code Comparable}
1433   * keys.</b> Proper calls will resolve to the version in {@code ImmutableSortedMap}, not this
1434   * dummy version.
1435   *
1436   * @throws UnsupportedOperationException always
1437   * @deprecated <b>Pass keys of type {@code Comparable} to use {@link
1438   *     ImmutableSortedMap#of(Comparable, Object, Comparable, Object, Comparable, Object,
1439   *     Comparable, Object, Comparable, Object)}.</b>
1440   */
1441  @DoNotCall("Pass keys of type Comparable")
1442  @Deprecated
1443  public static <K, V> ImmutableSortedMap<K, V> of(
1444      K k1,
1445      V v1,
1446      K k2,
1447      V v2,
1448      K k3,
1449      V v3,
1450      K k4,
1451      V v4,
1452      K k5,
1453      V v5,
1454      K k6,
1455      V v6,
1456      K k7,
1457      V v7,
1458      K k8,
1459      V v8,
1460      K k9,
1461      V v9) {
1462    throw new UnsupportedOperationException();
1463  }
1464
1465  /**
1466   * Not supported. <b>You are attempting to create a map that may contain non-{@code Comparable}
1467   * keys.</b> Proper calls will resolve to the version in {@code ImmutableSortedMap}, not this
1468   * dummy version.
1469   *
1470   * @throws UnsupportedOperationException always
1471   * @deprecated <b>Pass keys of type {@code Comparable} to use {@link
1472   *     ImmutableSortedMap#of(Comparable, Object, Comparable, Object, Comparable, Object,
1473   *     Comparable, Object, Comparable, Object)}.</b>
1474   */
1475  @DoNotCall("Pass keys of type Comparable")
1476  @Deprecated
1477  public static <K, V> ImmutableSortedMap<K, V> of(
1478      K k1,
1479      V v1,
1480      K k2,
1481      V v2,
1482      K k3,
1483      V v3,
1484      K k4,
1485      V v4,
1486      K k5,
1487      V v5,
1488      K k6,
1489      V v6,
1490      K k7,
1491      V v7,
1492      K k8,
1493      V v8,
1494      K k9,
1495      V v9,
1496      K k10,
1497      V v10) {
1498    throw new UnsupportedOperationException();
1499  }
1500
1501  /**
1502   * Not supported. Use {@code ImmutableSortedMap.copyOf(ImmutableMap.ofEntries(...))}.
1503   *
1504   * @deprecated Use {@code ImmutableSortedMap.copyOf(ImmutableMap.ofEntries(...))}.
1505   */
1506  @DoNotCall("ImmutableSortedMap.ofEntries not currently available; use ImmutableSortedMap.copyOf")
1507  @Deprecated
1508  @SafeVarargs
1509  public static <K, V> ImmutableSortedMap<K, V> ofEntries(
1510      Entry<? extends K, ? extends V>... entries) {
1511    throw new UnsupportedOperationException();
1512  }
1513}