001/*
002 * Copyright (C) 2008 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.ObjectArrays.checkElementsNotNull;
022
023import com.google.common.annotations.GwtCompatible;
024import com.google.common.annotations.GwtIncompatible;
025import com.google.common.annotations.J2ktIncompatible;
026import com.google.errorprone.annotations.CanIgnoreReturnValue;
027import com.google.errorprone.annotations.DoNotCall;
028import com.google.errorprone.annotations.concurrent.LazyInit;
029import java.io.InvalidObjectException;
030import java.io.ObjectInputStream;
031import java.io.Serializable;
032import java.util.Arrays;
033import java.util.Collection;
034import java.util.Collections;
035import java.util.Comparator;
036import java.util.Iterator;
037import java.util.NavigableSet;
038import java.util.SortedSet;
039import java.util.stream.Collector;
040import javax.annotation.CheckForNull;
041import org.checkerframework.checker.nullness.qual.Nullable;
042
043/**
044 * A {@link NavigableSet} whose contents will never change, with many other important properties
045 * detailed at {@link ImmutableCollection}.
046 *
047 * <p><b>Warning:</b> as with any sorted collection, you are strongly advised not to use a {@link
048 * Comparator} or {@link Comparable} type whose comparison behavior is <i>inconsistent with
049 * equals</i>. That is, {@code a.compareTo(b)} or {@code comparator.compare(a, b)} should equal zero
050 * <i>if and only if</i> {@code a.equals(b)}. If this advice is not followed, the resulting
051 * collection will not correctly obey its specification.
052 *
053 * <p>See the Guava User Guide article on <a href=
054 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>.
055 *
056 * @author Jared Levy
057 * @author Louis Wasserman
058 * @since 2.0 (implements {@code NavigableSet} since 12.0)
059 */
060// TODO(benyu): benchmark and optimize all creation paths, which are a mess now
061@GwtCompatible(serializable = true, emulated = true)
062@SuppressWarnings("serial") // we're overriding default serialization
063@ElementTypesAreNonnullByDefault
064public abstract class ImmutableSortedSet<E> extends ImmutableSet<E>
065    implements NavigableSet<E>, SortedIterable<E> {
066  /**
067   * Returns a {@code Collector} that accumulates the input elements into a new {@code
068   * ImmutableSortedSet}, ordered by the specified comparator.
069   *
070   * <p>If the elements contain duplicates (according to the comparator), only the first duplicate
071   * in encounter order will appear in the result.
072   *
073   * @since 33.2.0 (available since 21.0 in guava-jre)
074   */
075  @SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"})
076  @IgnoreJRERequirement // Users will use this only if they're already using streams.
077  public static <E> Collector<E, ?, ImmutableSortedSet<E>> toImmutableSortedSet(
078      Comparator<? super E> comparator) {
079    return CollectCollectors.toImmutableSortedSet(comparator);
080  }
081
082  static <E> RegularImmutableSortedSet<E> emptySet(Comparator<? super E> comparator) {
083    if (Ordering.natural().equals(comparator)) {
084      @SuppressWarnings("unchecked") // The natural-ordered empty set supports all types.
085      RegularImmutableSortedSet<E> result =
086          (RegularImmutableSortedSet<E>) RegularImmutableSortedSet.NATURAL_EMPTY_SET;
087      return result;
088    } else {
089      return new RegularImmutableSortedSet<>(ImmutableList.of(), comparator);
090    }
091  }
092
093  /**
094   * Returns the empty immutable sorted set.
095   *
096   * <p><b>Performance note:</b> the instance returned is a singleton.
097   */
098  @SuppressWarnings("unchecked") // The natural-ordered empty set supports all types.
099  public static <E> ImmutableSortedSet<E> of() {
100    return (ImmutableSortedSet<E>) RegularImmutableSortedSet.NATURAL_EMPTY_SET;
101  }
102
103  /** Returns an immutable sorted set containing a single element. */
104  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E e1) {
105    return new RegularImmutableSortedSet<>(ImmutableList.of(e1), Ordering.natural());
106  }
107
108  /**
109   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
110   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
111   * one specified is included.
112   *
113   * @throws NullPointerException if any element is null
114   */
115  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E e1, E e2) {
116    return construct(Ordering.natural(), 2, e1, e2);
117  }
118
119  /**
120   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
121   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
122   * one specified is included.
123   *
124   * @throws NullPointerException if any element is null
125   */
126  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E e1, E e2, E e3) {
127    return construct(Ordering.natural(), 3, e1, e2, e3);
128  }
129
130  /**
131   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
132   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
133   * one specified is included.
134   *
135   * @throws NullPointerException if any element is null
136   */
137  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E e1, E e2, E e3, E e4) {
138    return construct(Ordering.natural(), 4, e1, e2, e3, e4);
139  }
140
141  /**
142   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
143   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
144   * one specified is included.
145   *
146   * @throws NullPointerException if any element is null
147   */
148  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
149      E e1, E e2, E e3, E e4, E e5) {
150    return construct(Ordering.natural(), 5, e1, e2, e3, e4, e5);
151  }
152
153  /**
154   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
155   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
156   * one specified is included.
157   *
158   * @throws NullPointerException if any element is null
159   * @since 3.0 (source-compatible since 2.0)
160   */
161  @SuppressWarnings("unchecked")
162  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
163      E e1, E e2, E e3, E e4, E e5, E e6, E... remaining) {
164    Comparable<?>[] contents = new Comparable<?>[6 + remaining.length];
165    contents[0] = e1;
166    contents[1] = e2;
167    contents[2] = e3;
168    contents[3] = e4;
169    contents[4] = e5;
170    contents[5] = e6;
171    System.arraycopy(remaining, 0, contents, 6, remaining.length);
172    return construct(Ordering.natural(), contents.length, (E[]) contents);
173  }
174
175  // TODO(kevinb): Consider factory methods that reject duplicates
176
177  /**
178   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
179   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
180   * one specified is included.
181   *
182   * @throws NullPointerException if any of {@code elements} is null
183   * @since 3.0
184   */
185  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> copyOf(E[] elements) {
186    return construct(Ordering.natural(), elements.length, elements.clone());
187  }
188
189  /**
190   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
191   * When multiple elements are equivalent according to {@code compareTo()}, only the first one
192   * specified is included. To create a copy of a {@code SortedSet} that preserves the comparator,
193   * call {@link #copyOfSorted} instead. This method iterates over {@code elements} at most once.
194   *
195   * <p>Note that if {@code s} is a {@code Set<String>}, then {@code ImmutableSortedSet.copyOf(s)}
196   * returns an {@code ImmutableSortedSet<String>} containing each of the strings in {@code s},
197   * while {@code ImmutableSortedSet.of(s)} returns an {@code ImmutableSortedSet<Set<String>>}
198   * containing one element (the given set itself).
199   *
200   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
201   * safe to do so. The exact circumstances under which a copy will or will not be performed are
202   * undocumented and subject to change.
203   *
204   * <p>This method is not type-safe, as it may be called on elements that are not mutually
205   * comparable.
206   *
207   * @throws ClassCastException if the elements are not mutually comparable
208   * @throws NullPointerException if any of {@code elements} is null
209   */
210  public static <E> ImmutableSortedSet<E> copyOf(Iterable<? extends E> elements) {
211    // Hack around E not being a subtype of Comparable.
212    // Unsafe, see ImmutableSortedSetFauxverideShim.
213    @SuppressWarnings("unchecked")
214    Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable<?>>natural();
215    return copyOf(naturalOrder, elements);
216  }
217
218  /**
219   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
220   * When multiple elements are equivalent according to {@code compareTo()}, only the first one
221   * specified is included. To create a copy of a {@code SortedSet} that preserves the comparator,
222   * call {@link #copyOfSorted} instead. This method iterates over {@code elements} at most once.
223   *
224   * <p>Note that if {@code s} is a {@code Set<String>}, then {@code ImmutableSortedSet.copyOf(s)}
225   * returns an {@code ImmutableSortedSet<String>} containing each of the strings in {@code s},
226   * while {@code ImmutableSortedSet.of(s)} returns an {@code ImmutableSortedSet<Set<String>>}
227   * containing one element (the given set itself).
228   *
229   * <p><b>Note:</b> Despite what the method name suggests, if {@code elements} is an {@code
230   * ImmutableSortedSet}, it may be returned instead of a copy.
231   *
232   * <p>This method is not type-safe, as it may be called on elements that are not mutually
233   * comparable.
234   *
235   * <p>This method is safe to use even when {@code elements} is a synchronized or concurrent
236   * collection that is currently being modified by another thread.
237   *
238   * @throws ClassCastException if the elements are not mutually comparable
239   * @throws NullPointerException if any of {@code elements} is null
240   * @since 7.0 (source-compatible since 2.0)
241   */
242  public static <E> ImmutableSortedSet<E> copyOf(Collection<? extends E> elements) {
243    // Hack around E not being a subtype of Comparable.
244    // Unsafe, see ImmutableSortedSetFauxverideShim.
245    @SuppressWarnings("unchecked")
246    Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable<?>>natural();
247    return copyOf(naturalOrder, elements);
248  }
249
250  /**
251   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
252   * When multiple elements are equivalent according to {@code compareTo()}, only the first one
253   * specified is included.
254   *
255   * <p>This method is not type-safe, as it may be called on elements that are not mutually
256   * comparable.
257   *
258   * @throws ClassCastException if the elements are not mutually comparable
259   * @throws NullPointerException if any of {@code elements} is null
260   */
261  public static <E> ImmutableSortedSet<E> copyOf(Iterator<? extends E> elements) {
262    // Hack around E not being a subtype of Comparable.
263    // Unsafe, see ImmutableSortedSetFauxverideShim.
264    @SuppressWarnings("unchecked")
265    Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable<?>>natural();
266    return copyOf(naturalOrder, elements);
267  }
268
269  /**
270   * Returns an immutable sorted set containing the given elements sorted by the given {@code
271   * Comparator}. When multiple elements are equivalent according to {@code compareTo()}, only the
272   * first one specified is included.
273   *
274   * @throws NullPointerException if {@code comparator} or any of {@code elements} is null
275   */
276  public static <E> ImmutableSortedSet<E> copyOf(
277      Comparator<? super E> comparator, Iterator<? extends E> elements) {
278    return new Builder<E>(comparator).addAll(elements).build();
279  }
280
281  /**
282   * Returns an immutable sorted set containing the given elements sorted by the given {@code
283   * Comparator}. When multiple elements are equivalent according to {@code compare()}, only the
284   * first one specified is included. This method iterates over {@code elements} at most once.
285   *
286   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
287   * safe to do so. The exact circumstances under which a copy will or will not be performed are
288   * undocumented and subject to change.
289   *
290   * @throws NullPointerException if {@code comparator} or any of {@code elements} is null
291   */
292  public static <E> ImmutableSortedSet<E> copyOf(
293      Comparator<? super E> comparator, Iterable<? extends E> elements) {
294    checkNotNull(comparator);
295    boolean hasSameComparator = SortedIterables.hasSameComparator(comparator, elements);
296
297    if (hasSameComparator && (elements instanceof ImmutableSortedSet)) {
298      @SuppressWarnings("unchecked")
299      ImmutableSortedSet<E> original = (ImmutableSortedSet<E>) elements;
300      if (!original.isPartialView()) {
301        return original;
302      }
303    }
304    @SuppressWarnings("unchecked") // elements only contains E's; it's safe.
305    E[] array = (E[]) Iterables.toArray(elements);
306    return construct(comparator, array.length, array);
307  }
308
309  /**
310   * Returns an immutable sorted set containing the given elements sorted by the given {@code
311   * Comparator}. When multiple elements are equivalent according to {@code compareTo()}, only the
312   * first one specified is included.
313   *
314   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
315   * safe to do so. The exact circumstances under which a copy will or will not be performed are
316   * undocumented and subject to change.
317   *
318   * <p>This method is safe to use even when {@code elements} is a synchronized or concurrent
319   * collection that is currently being modified by another thread.
320   *
321   * @throws NullPointerException if {@code comparator} or any of {@code elements} is null
322   * @since 7.0 (source-compatible since 2.0)
323   */
324  public static <E> ImmutableSortedSet<E> copyOf(
325      Comparator<? super E> comparator, Collection<? extends E> elements) {
326    return copyOf(comparator, (Iterable<? extends E>) elements);
327  }
328
329  /**
330   * Returns an immutable sorted set containing the elements of a sorted set, sorted by the same
331   * {@code Comparator}. That behavior differs from {@link #copyOf(Iterable)}, which always uses the
332   * natural ordering of the elements.
333   *
334   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
335   * safe to do so. The exact circumstances under which a copy will or will not be performed are
336   * undocumented and subject to change.
337   *
338   * <p>This method is safe to use even when {@code sortedSet} is a synchronized or concurrent
339   * collection that is currently being modified by another thread.
340   *
341   * @throws NullPointerException if {@code sortedSet} or any of its elements is null
342   */
343  public static <E> ImmutableSortedSet<E> copyOfSorted(SortedSet<E> sortedSet) {
344    Comparator<? super E> comparator = SortedIterables.comparator(sortedSet);
345    ImmutableList<E> list = ImmutableList.copyOf(sortedSet);
346    if (list.isEmpty()) {
347      return emptySet(comparator);
348    } else {
349      return new RegularImmutableSortedSet<>(list, comparator);
350    }
351  }
352
353  /**
354   * Constructs an {@code ImmutableSortedSet} from the first {@code n} elements of {@code contents}.
355   * If {@code k} is the size of the returned {@code ImmutableSortedSet}, then the sorted unique
356   * elements are in the first {@code k} positions of {@code contents}, and {@code contents[i] ==
357   * null} for {@code k <= i < n}.
358   *
359   * <p>This method takes ownership of {@code contents}; do not modify {@code contents} after this
360   * returns.
361   *
362   * @throws NullPointerException if any of the first {@code n} elements of {@code contents} is null
363   */
364  static <E> ImmutableSortedSet<E> construct(
365      Comparator<? super E> comparator, int n, E... contents) {
366    if (n == 0) {
367      return emptySet(comparator);
368    }
369    checkElementsNotNull(contents, n);
370    Arrays.sort(contents, 0, n, comparator);
371    int uniques = 1;
372    for (int i = 1; i < n; i++) {
373      E cur = contents[i];
374      E prev = contents[uniques - 1];
375      if (comparator.compare(cur, prev) != 0) {
376        contents[uniques++] = cur;
377      }
378    }
379    Arrays.fill(contents, uniques, n, null);
380    if (uniques < contents.length / 2) {
381      // Deduplication eliminated many of the elements.  We don't want to retain an arbitrarily
382      // large array relative to the number of elements, so we cap the ratio.
383      contents = Arrays.copyOf(contents, uniques);
384    }
385    return new RegularImmutableSortedSet<E>(
386        ImmutableList.<E>asImmutableList(contents, uniques), comparator);
387  }
388
389  /**
390   * Returns a builder that creates immutable sorted sets with an explicit comparator. If the
391   * comparator has a more general type than the set being generated, such as creating a {@code
392   * SortedSet<Integer>} with a {@code Comparator<Number>}, use the {@link Builder} constructor
393   * instead.
394   *
395   * @throws NullPointerException if {@code comparator} is null
396   */
397  public static <E> Builder<E> orderedBy(Comparator<E> comparator) {
398    return new Builder<>(comparator);
399  }
400
401  /**
402   * Returns a builder that creates immutable sorted sets whose elements are ordered by the reverse
403   * of their natural ordering.
404   */
405  public static <E extends Comparable<?>> Builder<E> reverseOrder() {
406    return new Builder<>(Collections.reverseOrder());
407  }
408
409  /**
410   * Returns a builder that creates immutable sorted sets whose elements are ordered by their
411   * natural ordering. The sorted sets use {@link Ordering#natural()} as the comparator. This method
412   * provides more type-safety than {@link #builder}, as it can be called only for classes that
413   * implement {@link Comparable}.
414   */
415  public static <E extends Comparable<?>> Builder<E> naturalOrder() {
416    return new Builder<>(Ordering.natural());
417  }
418
419  /**
420   * A builder for creating immutable sorted set instances, especially {@code public static final}
421   * sets ("constant sets"), with a given comparator. Example:
422   *
423   * <pre>{@code
424   * public static final ImmutableSortedSet<Number> LUCKY_NUMBERS =
425   *     new ImmutableSortedSet.Builder<Number>(ODDS_FIRST_COMPARATOR)
426   *         .addAll(SINGLE_DIGIT_PRIMES)
427   *         .add(42)
428   *         .build();
429   * }</pre>
430   *
431   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
432   * multiple sets in series. Each set is a superset of the set created before it.
433   *
434   * @since 2.0
435   */
436  public static final class Builder<E> extends ImmutableSet.Builder<E> {
437    private final Comparator<? super E> comparator;
438
439    /**
440     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
441     * ImmutableSortedSet#orderedBy}.
442     */
443    /*
444     * TODO(cpovirk): use Object[] instead of E[] in the mainline? (The backport is different and
445     * doesn't need this suppression, but we keep it to minimize diffs.) Generally be more clear
446     * about when we have an Object[] vs. a Comparable[] or other array type in internalArray? If we
447     * used Object[], we might be able to optimize toArray() to use clone() sometimes. (See
448     * cl/592273615 and cl/592273683.)
449     */
450    public Builder(Comparator<? super E> comparator) {
451      this.comparator = checkNotNull(comparator);
452    }
453
454    Builder(Comparator<? super E> comparator, int expectedKeys) {
455      super(expectedKeys, false);
456      this.comparator = checkNotNull(comparator);
457    }
458
459    /**
460     * Adds {@code element} to the {@code ImmutableSortedSet}. If the {@code ImmutableSortedSet}
461     * already contains {@code element}, then {@code add} has no effect. (only the previously added
462     * element is retained).
463     *
464     * @param element the element to add
465     * @return this {@code Builder} object
466     * @throws NullPointerException if {@code element} is null
467     */
468    @CanIgnoreReturnValue
469    @Override
470    public Builder<E> add(E element) {
471      super.add(element);
472      return this;
473    }
474
475    /**
476     * Adds each element of {@code elements} to the {@code ImmutableSortedSet}, ignoring duplicate
477     * elements (only the first duplicate element is added).
478     *
479     * @param elements the elements to add
480     * @return this {@code Builder} object
481     * @throws NullPointerException if {@code elements} contains a null element
482     */
483    @CanIgnoreReturnValue
484    @Override
485    public Builder<E> add(E... elements) {
486      super.add(elements);
487      return this;
488    }
489
490    /**
491     * Adds each element of {@code elements} to the {@code ImmutableSortedSet}, ignoring duplicate
492     * elements (only the first duplicate element is added).
493     *
494     * @param elements the elements to add to the {@code ImmutableSortedSet}
495     * @return this {@code Builder} object
496     * @throws NullPointerException if {@code elements} contains a null element
497     */
498    @CanIgnoreReturnValue
499    @Override
500    public Builder<E> addAll(Iterable<? extends E> elements) {
501      super.addAll(elements);
502      return this;
503    }
504
505    /**
506     * Adds each element of {@code elements} to the {@code ImmutableSortedSet}, ignoring duplicate
507     * elements (only the first duplicate element is added).
508     *
509     * @param elements the elements to add to the {@code ImmutableSortedSet}
510     * @return this {@code Builder} object
511     * @throws NullPointerException if {@code elements} contains a null element
512     */
513    @CanIgnoreReturnValue
514    @Override
515    public Builder<E> addAll(Iterator<? extends E> elements) {
516      super.addAll(elements);
517      return this;
518    }
519
520    @CanIgnoreReturnValue
521    @Override
522    Builder<E> combine(ImmutableSet.Builder<E> builder) {
523      super.combine(builder);
524      return this;
525    }
526
527    /**
528     * Returns a newly-created {@code ImmutableSortedSet} based on the contents of the {@code
529     * Builder} and its comparator.
530     */
531    @Override
532    public ImmutableSortedSet<E> build() {
533      @SuppressWarnings("unchecked") // we're careful to put only E's in here
534      E[] contentsArray = (E[]) contents;
535      ImmutableSortedSet<E> result = construct(comparator, size, contentsArray);
536      this.size = result.size(); // we eliminated duplicates in-place in contentsArray
537      this.forceCopy = true;
538      return result;
539    }
540  }
541
542  int unsafeCompare(Object a, @CheckForNull Object b) {
543    return unsafeCompare(comparator, a, b);
544  }
545
546  static int unsafeCompare(Comparator<?> comparator, Object a, @CheckForNull Object b) {
547    // Pretend the comparator can compare anything. If it turns out it can't
548    // compare a and b, we should get a CCE or NPE on the subsequent line. Only methods
549    // that are spec'd to throw CCE and NPE should call this.
550    @SuppressWarnings({"unchecked", "nullness"})
551    Comparator<@Nullable Object> unsafeComparator = (Comparator<@Nullable Object>) comparator;
552    return unsafeComparator.compare(a, b);
553  }
554
555  final transient Comparator<? super E> comparator;
556
557  ImmutableSortedSet(Comparator<? super E> comparator) {
558    this.comparator = comparator;
559  }
560
561  /**
562   * Returns the comparator that orders the elements, which is {@link Ordering#natural()} when the
563   * natural ordering of the elements is used. Note that its behavior is not consistent with {@link
564   * SortedSet#comparator()}, which returns {@code null} to indicate natural ordering.
565   */
566  @Override
567  public Comparator<? super E> comparator() {
568    return comparator;
569  }
570
571  @Override // needed to unify the iterator() methods in Collection and SortedIterable
572  public abstract UnmodifiableIterator<E> iterator();
573
574  /**
575   * {@inheritDoc}
576   *
577   * <p>This method returns a serializable {@code ImmutableSortedSet}.
578   *
579   * <p>The {@link SortedSet#headSet} documentation states that a subset of a subset throws an
580   * {@link IllegalArgumentException} if passed a {@code toElement} greater than an earlier {@code
581   * toElement}. However, this method doesn't throw an exception in that situation, but instead
582   * keeps the original {@code toElement}.
583   */
584  @Override
585  public ImmutableSortedSet<E> headSet(E toElement) {
586    return headSet(toElement, false);
587  }
588
589  /** @since 12.0 */
590  @Override
591  public ImmutableSortedSet<E> headSet(E toElement, boolean inclusive) {
592    return headSetImpl(checkNotNull(toElement), inclusive);
593  }
594
595  /**
596   * {@inheritDoc}
597   *
598   * <p>This method returns a serializable {@code ImmutableSortedSet}.
599   *
600   * <p>The {@link SortedSet#subSet} documentation states that a subset of a subset throws an {@link
601   * IllegalArgumentException} if passed a {@code fromElement} smaller than an earlier {@code
602   * fromElement}. However, this method doesn't throw an exception in that situation, but instead
603   * keeps the original {@code fromElement}. Similarly, this method keeps the original {@code
604   * toElement}, instead of throwing an exception, if passed a {@code toElement} greater than an
605   * earlier {@code toElement}.
606   */
607  @Override
608  public ImmutableSortedSet<E> subSet(E fromElement, E toElement) {
609    return subSet(fromElement, true, toElement, false);
610  }
611
612  /** @since 12.0 */
613  @GwtIncompatible // NavigableSet
614  @Override
615  public ImmutableSortedSet<E> subSet(
616      E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
617    checkNotNull(fromElement);
618    checkNotNull(toElement);
619    checkArgument(comparator.compare(fromElement, toElement) <= 0);
620    return subSetImpl(fromElement, fromInclusive, toElement, toInclusive);
621  }
622
623  /**
624   * {@inheritDoc}
625   *
626   * <p>This method returns a serializable {@code ImmutableSortedSet}.
627   *
628   * <p>The {@link SortedSet#tailSet} documentation states that a subset of a subset throws an
629   * {@link IllegalArgumentException} if passed a {@code fromElement} smaller than an earlier {@code
630   * fromElement}. However, this method doesn't throw an exception in that situation, but instead
631   * keeps the original {@code fromElement}.
632   */
633  @Override
634  public ImmutableSortedSet<E> tailSet(E fromElement) {
635    return tailSet(fromElement, true);
636  }
637
638  /** @since 12.0 */
639  @Override
640  public ImmutableSortedSet<E> tailSet(E fromElement, boolean inclusive) {
641    return tailSetImpl(checkNotNull(fromElement), inclusive);
642  }
643
644  /*
645   * These methods perform most headSet, subSet, and tailSet logic, besides
646   * parameter validation.
647   */
648  abstract ImmutableSortedSet<E> headSetImpl(E toElement, boolean inclusive);
649
650  abstract ImmutableSortedSet<E> subSetImpl(
651      E fromElement, boolean fromInclusive, E toElement, boolean toInclusive);
652
653  abstract ImmutableSortedSet<E> tailSetImpl(E fromElement, boolean inclusive);
654
655  /** @since 12.0 */
656  @GwtIncompatible // NavigableSet
657  @Override
658  @CheckForNull
659  public E lower(E e) {
660    return Iterators.<@Nullable E>getNext(headSet(e, false).descendingIterator(), null);
661  }
662
663  /** @since 12.0 */
664  @Override
665  @CheckForNull
666  public E floor(E e) {
667    return Iterators.<@Nullable E>getNext(headSet(e, true).descendingIterator(), null);
668  }
669
670  /** @since 12.0 */
671  @Override
672  @CheckForNull
673  public E ceiling(E e) {
674    return Iterables.<@Nullable E>getFirst(tailSet(e, true), null);
675  }
676
677  /** @since 12.0 */
678  @GwtIncompatible // NavigableSet
679  @Override
680  @CheckForNull
681  public E higher(E e) {
682    return Iterables.<@Nullable E>getFirst(tailSet(e, false), null);
683  }
684
685  @Override
686  public E first() {
687    return iterator().next();
688  }
689
690  @Override
691  public E last() {
692    return descendingIterator().next();
693  }
694
695  /**
696   * Guaranteed to throw an exception and leave the set unmodified.
697   *
698   * @since 12.0
699   * @throws UnsupportedOperationException always
700   * @deprecated Unsupported operation.
701   */
702  @CanIgnoreReturnValue
703  @Deprecated
704  @GwtIncompatible // NavigableSet
705  @Override
706  @DoNotCall("Always throws UnsupportedOperationException")
707  @CheckForNull
708  public final E pollFirst() {
709    throw new UnsupportedOperationException();
710  }
711
712  /**
713   * Guaranteed to throw an exception and leave the set unmodified.
714   *
715   * @since 12.0
716   * @throws UnsupportedOperationException always
717   * @deprecated Unsupported operation.
718   */
719  @CanIgnoreReturnValue
720  @Deprecated
721  @GwtIncompatible // NavigableSet
722  @Override
723  @DoNotCall("Always throws UnsupportedOperationException")
724  @CheckForNull
725  public final E pollLast() {
726    throw new UnsupportedOperationException();
727  }
728
729  @GwtIncompatible // NavigableSet
730  @LazyInit
731  @CheckForNull
732  transient ImmutableSortedSet<E> descendingSet;
733
734  /** @since 12.0 */
735  @GwtIncompatible // NavigableSet
736  @Override
737  public ImmutableSortedSet<E> descendingSet() {
738    // racy single-check idiom
739    ImmutableSortedSet<E> result = descendingSet;
740    if (result == null) {
741      result = descendingSet = createDescendingSet();
742      result.descendingSet = this;
743    }
744    return result;
745  }
746
747  // Most classes should implement this as new DescendingImmutableSortedSet<E>(this),
748  // but we push down that implementation because ProGuard can't eliminate it even when it's always
749  // overridden.
750  @GwtIncompatible // NavigableSet
751  abstract ImmutableSortedSet<E> createDescendingSet();
752
753  /** @since 12.0 */
754  @GwtIncompatible // NavigableSet
755  @Override
756  public abstract UnmodifiableIterator<E> descendingIterator();
757
758  /** Returns the position of an element within the set, or -1 if not present. */
759  abstract int indexOf(@CheckForNull Object target);
760
761  /*
762   * This class is used to serialize all ImmutableSortedSet instances,
763   * regardless of implementation type. It captures their "logical contents"
764   * only. This is necessary to ensure that the existence of a particular
765   * implementation type is an implementation detail.
766   */
767  @J2ktIncompatible // serialization
768  private static class SerializedForm<E> implements Serializable {
769    final Comparator<? super E> comparator;
770    final Object[] elements;
771
772    public SerializedForm(Comparator<? super E> comparator, Object[] elements) {
773      this.comparator = comparator;
774      this.elements = elements;
775    }
776
777    @SuppressWarnings("unchecked")
778    Object readResolve() {
779      return new Builder<E>(comparator).add((E[]) elements).build();
780    }
781
782    private static final long serialVersionUID = 0;
783  }
784
785  @J2ktIncompatible // serialization
786  private void readObject(ObjectInputStream unused) throws InvalidObjectException {
787    throw new InvalidObjectException("Use SerializedForm");
788  }
789
790  @Override
791  @J2ktIncompatible // serialization
792  Object writeReplace() {
793    return new SerializedForm<E>(comparator, toArray());
794  }
795
796  /**
797   * Not supported. Use {@link #toImmutableSortedSet} instead. This method exists only to hide
798   * {@link ImmutableSet#toImmutableSet} from consumers of {@code ImmutableSortedSet}.
799   *
800   * @throws UnsupportedOperationException always
801   * @deprecated Use {@link ImmutableSortedSet#toImmutableSortedSet}.
802   * @since 33.2.0 (available since 21.0 in guava-jre)
803   */
804  @DoNotCall("Use toImmutableSortedSet")
805  @Deprecated
806  @SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"})
807  @IgnoreJRERequirement // Users will use this only if they're already using streams.
808  public static <E> Collector<E, ?, ImmutableSet<E>> toImmutableSet() {
809    throw new UnsupportedOperationException();
810  }
811
812  /**
813   * Not supported. Use {@link #naturalOrder}, which offers better type-safety, instead. This method
814   * exists only to hide {@link ImmutableSet#builder} from consumers of {@code ImmutableSortedSet}.
815   *
816   * @throws UnsupportedOperationException always
817   * @deprecated Use {@link ImmutableSortedSet#naturalOrder}, which offers better type-safety.
818   */
819  @DoNotCall("Use naturalOrder")
820  @Deprecated
821  public static <E> ImmutableSortedSet.Builder<E> builder() {
822    throw new UnsupportedOperationException();
823  }
824
825  /**
826   * Not supported. This method exists only to hide {@link ImmutableSet#builderWithExpectedSize}
827   * from consumers of {@code ImmutableSortedSet}.
828   *
829   * @throws UnsupportedOperationException always
830   * @deprecated Not supported by ImmutableSortedSet.
831   */
832  @DoNotCall("Use naturalOrder (which does not accept an expected size)")
833  @Deprecated
834  public static <E> ImmutableSortedSet.Builder<E> builderWithExpectedSize(int expectedSize) {
835    throw new UnsupportedOperationException();
836  }
837
838  /**
839   * Not supported. <b>You are attempting to create a set that may contain a non-{@code Comparable}
840   * element.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
841   * dummy version.
842   *
843   * @throws UnsupportedOperationException always
844   * @deprecated <b>Pass a parameter of type {@code Comparable} to use {@link
845   *     ImmutableSortedSet#of(Comparable)}.</b>
846   */
847  @DoNotCall("Pass a parameter of type Comparable")
848  @Deprecated
849  public static <E> ImmutableSortedSet<E> of(E e1) {
850    throw new UnsupportedOperationException();
851  }
852
853  /**
854   * Not supported. <b>You are attempting to create a set that may contain a non-{@code Comparable}
855   * element.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
856   * dummy version.
857   *
858   * @throws UnsupportedOperationException always
859   * @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
860   *     ImmutableSortedSet#of(Comparable, Comparable)}.</b>
861   */
862  @DoNotCall("Pass parameters of type Comparable")
863  @Deprecated
864  public static <E> ImmutableSortedSet<E> of(E e1, E e2) {
865    throw new UnsupportedOperationException();
866  }
867
868  /**
869   * Not supported. <b>You are attempting to create a set that may contain a non-{@code Comparable}
870   * element.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
871   * dummy version.
872   *
873   * @throws UnsupportedOperationException always
874   * @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
875   *     ImmutableSortedSet#of(Comparable, Comparable, Comparable)}.</b>
876   */
877  @DoNotCall("Pass parameters of type Comparable")
878  @Deprecated
879  public static <E> ImmutableSortedSet<E> of(E e1, E e2, E e3) {
880    throw new UnsupportedOperationException();
881  }
882
883  /**
884   * Not supported. <b>You are attempting to create a set that may contain a non-{@code Comparable}
885   * element.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
886   * dummy version.
887   *
888   * @throws UnsupportedOperationException always
889   * @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
890   *     ImmutableSortedSet#of(Comparable, Comparable, Comparable, Comparable)}. </b>
891   */
892  @DoNotCall("Pass parameters of type Comparable")
893  @Deprecated
894  public static <E> ImmutableSortedSet<E> of(E e1, E e2, E e3, E e4) {
895    throw new UnsupportedOperationException();
896  }
897
898  /**
899   * Not supported. <b>You are attempting to create a set that may contain a non-{@code Comparable}
900   * element.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
901   * dummy version.
902   *
903   * @throws UnsupportedOperationException always
904   * @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
905   *     ImmutableSortedSet#of( Comparable, Comparable, Comparable, Comparable, Comparable)}. </b>
906   */
907  @DoNotCall("Pass parameters of type Comparable")
908  @Deprecated
909  public static <E> ImmutableSortedSet<E> of(E e1, E e2, E e3, E e4, E e5) {
910    throw new UnsupportedOperationException();
911  }
912
913  /**
914   * Not supported. <b>You are attempting to create a set that may contain a non-{@code Comparable}
915   * element.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
916   * dummy version.
917   *
918   * @throws UnsupportedOperationException always
919   * @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
920   *     ImmutableSortedSet#of(Comparable, Comparable, Comparable, Comparable, Comparable,
921   *     Comparable, Comparable...)}. </b>
922   */
923  @DoNotCall("Pass parameters of type Comparable")
924  @Deprecated
925  public static <E> ImmutableSortedSet<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E... remaining) {
926    throw new UnsupportedOperationException();
927  }
928
929  /**
930   * Not supported. <b>You are attempting to create a set that may contain non-{@code Comparable}
931   * elements.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
932   * dummy version.
933   *
934   * @throws UnsupportedOperationException always
935   * @deprecated <b>Pass parameters of type {@code Comparable} to use {@link
936   *     ImmutableSortedSet#copyOf(Comparable[])}.</b>
937   */
938  @DoNotCall("Pass parameters of type Comparable")
939  @Deprecated
940  // The usage of "Z" here works around bugs in Javadoc (JDK-8318093) and JDiff.
941  public static <Z> ImmutableSortedSet<Z> copyOf(Z[] elements) {
942    throw new UnsupportedOperationException();
943  }
944
945  private static final long serialVersionUID = 0xdecaf;
946}