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