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