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;
022import static java.lang.System.arraycopy;
023import static java.util.Arrays.sort;
024
025import com.google.common.annotations.GwtCompatible;
026import com.google.common.annotations.GwtIncompatible;
027import com.google.common.annotations.J2ktIncompatible;
028import com.google.errorprone.annotations.CanIgnoreReturnValue;
029import com.google.errorprone.annotations.DoNotCall;
030import com.google.errorprone.annotations.concurrent.LazyInit;
031import java.io.InvalidObjectException;
032import java.io.ObjectInputStream;
033import java.io.Serializable;
034import java.util.Arrays;
035import java.util.Collection;
036import java.util.Collections;
037import java.util.Comparator;
038import java.util.Iterator;
039import java.util.NavigableSet;
040import java.util.SortedSet;
041import java.util.stream.Collector;
042import org.checkerframework.checker.nullness.qual.Nullable;
043
044/**
045 * A {@link NavigableSet} whose contents will never change, with many other important properties
046 * detailed at {@link ImmutableCollection}.
047 *
048 * <p><b>Warning:</b> as with any sorted collection, you are strongly advised not to use a {@link
049 * Comparator} or {@link Comparable} type whose comparison behavior is <i>inconsistent with
050 * equals</i>. That is, {@code a.compareTo(b)} or {@code comparator.compare(a, b)} should equal zero
051 * <i>if and only if</i> {@code a.equals(b)}. If this advice is not followed, the resulting
052 * collection will not correctly obey its specification.
053 *
054 * <p>See the Guava User Guide article on <a href=
055 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>.
056 *
057 * @author Jared Levy
058 * @author Louis Wasserman
059 * @since 2.0 (implements {@code NavigableSet} since 12.0)
060 */
061// TODO(benyu): benchmark and optimize all creation paths, which are a mess now
062@GwtCompatible(serializable = true, emulated = true)
063@SuppressWarnings("serial") // we're overriding default serialization
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("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    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    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, @Nullable Object b) {
543    return unsafeCompare(comparator, a, b);
544  }
545
546  static int unsafeCompare(Comparator<?> comparator, Object a, @Nullable 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  /**
656   * @since 12.0
657   */
658  @GwtIncompatible // NavigableSet
659  @Override
660  public @Nullable E lower(E e) {
661    return Iterators.<@Nullable E>getNext(headSet(e, false).descendingIterator(), null);
662  }
663
664  /**
665   * @since 12.0
666   */
667  @Override
668  public @Nullable E floor(E e) {
669    return Iterators.<@Nullable E>getNext(headSet(e, true).descendingIterator(), null);
670  }
671
672  /**
673   * @since 12.0
674   */
675  @Override
676  public @Nullable E ceiling(E e) {
677    return Iterables.<@Nullable E>getFirst(tailSet(e, true), null);
678  }
679
680  /**
681   * @since 12.0
682   */
683  @GwtIncompatible // NavigableSet
684  @Override
685  public @Nullable E higher(E e) {
686    return Iterables.<@Nullable E>getFirst(tailSet(e, false), null);
687  }
688
689  @Override
690  public E first() {
691    return iterator().next();
692  }
693
694  @Override
695  public E last() {
696    return descendingIterator().next();
697  }
698
699  /**
700   * Guaranteed to throw an exception and leave the set unmodified.
701   *
702   * @since 12.0
703   * @throws UnsupportedOperationException always
704   * @deprecated Unsupported operation.
705   */
706  @CanIgnoreReturnValue
707  @Deprecated
708  @GwtIncompatible // NavigableSet
709  @Override
710  @DoNotCall("Always throws UnsupportedOperationException")
711  public final @Nullable E pollFirst() {
712    throw new UnsupportedOperationException();
713  }
714
715  /**
716   * Guaranteed to throw an exception and leave the set unmodified.
717   *
718   * @since 12.0
719   * @throws UnsupportedOperationException always
720   * @deprecated Unsupported operation.
721   */
722  @CanIgnoreReturnValue
723  @Deprecated
724  @GwtIncompatible // NavigableSet
725  @Override
726  @DoNotCall("Always throws UnsupportedOperationException")
727  public final @Nullable E pollLast() {
728    throw new UnsupportedOperationException();
729  }
730
731  @GwtIncompatible // NavigableSet
732  @LazyInit
733  transient @Nullable ImmutableSortedSet<E> descendingSet;
734
735  /** @since 12.0 */
736  @GwtIncompatible // NavigableSet
737  @Override
738  public ImmutableSortedSet<E> descendingSet() {
739    // racy single-check idiom
740    ImmutableSortedSet<E> result = descendingSet;
741    if (result == null) {
742      result = descendingSet = createDescendingSet();
743      result.descendingSet = this;
744    }
745    return result;
746  }
747
748  // Most classes should implement this as new DescendingImmutableSortedSet<E>(this),
749  // but we push down that implementation because ProGuard can't eliminate it even when it's always
750  // overridden.
751  @GwtIncompatible // NavigableSet
752  abstract ImmutableSortedSet<E> createDescendingSet();
753
754  /** @since 12.0 */
755  @GwtIncompatible // NavigableSet
756  @Override
757  public abstract UnmodifiableIterator<E> descendingIterator();
758
759  /** Returns the position of an element within the set, or -1 if not present. */
760  abstract int indexOf(@Nullable Object target);
761
762  /*
763   * This class is used to serialize all ImmutableSortedSet instances,
764   * regardless of implementation type. It captures their "logical contents"
765   * only. This is necessary to ensure that the existence of a particular
766   * implementation type is an implementation detail.
767   */
768  @J2ktIncompatible // serialization
769  private static class SerializedForm<E> implements Serializable {
770    final Comparator<? super E> comparator;
771    final Object[] elements;
772
773    public SerializedForm(Comparator<? super E> comparator, Object[] elements) {
774      this.comparator = comparator;
775      this.elements = elements;
776    }
777
778    @SuppressWarnings("unchecked")
779    Object readResolve() {
780      return new Builder<E>(comparator).add((E[]) elements).build();
781    }
782
783    private static final long serialVersionUID = 0;
784  }
785
786  @J2ktIncompatible // serialization
787  private void readObject(ObjectInputStream unused) throws InvalidObjectException {
788    throw new InvalidObjectException("Use SerializedForm");
789  }
790
791  @Override
792  @J2ktIncompatible // serialization
793  Object writeReplace() {
794    return new SerializedForm<E>(comparator, toArray());
795  }
796
797  /**
798   * Not supported. Use {@link #toImmutableSortedSet} instead. This method exists only to hide
799   * {@link ImmutableSet#toImmutableSet} from consumers of {@code ImmutableSortedSet}.
800   *
801   * @throws UnsupportedOperationException always
802   * @deprecated Use {@link ImmutableSortedSet#toImmutableSortedSet}.
803   * @since 33.2.0 (available since 21.0 in guava-jre)
804   */
805  @DoNotCall("Use toImmutableSortedSet")
806  @Deprecated
807  @SuppressWarnings("Java7ApiChecker")
808  @IgnoreJRERequirement // Users will use this only if they're already using streams.
809  public static <E> Collector<E, ?, ImmutableSet<E>> toImmutableSet() {
810    throw new UnsupportedOperationException();
811  }
812
813  /**
814   * Not supported. Use {@link #naturalOrder}, which offers better type-safety, instead. This method
815   * exists only to hide {@link ImmutableSet#builder} from consumers of {@code ImmutableSortedSet}.
816   *
817   * @throws UnsupportedOperationException always
818   * @deprecated Use {@link ImmutableSortedSet#naturalOrder}, which offers better type-safety.
819   */
820  @DoNotCall("Use naturalOrder")
821  @Deprecated
822  public static <E> ImmutableSortedSet.Builder<E> builder() {
823    throw new UnsupportedOperationException();
824  }
825
826  /**
827   * Not supported. This method exists only to hide {@link ImmutableSet#builderWithExpectedSize}
828   * from consumers of {@code ImmutableSortedSet}.
829   *
830   * @throws UnsupportedOperationException always
831   * @deprecated Not supported by ImmutableSortedSet.
832   */
833  @DoNotCall("Use naturalOrder (which does not accept an expected size)")
834  @Deprecated
835  public static <E> ImmutableSortedSet.Builder<E> builderWithExpectedSize(int expectedSize) {
836    throw new UnsupportedOperationException();
837  }
838
839  /**
840   * Not supported. <b>You are attempting to create a set that may contain a non-{@code Comparable}
841   * element.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
842   * dummy version.
843   *
844   * @throws UnsupportedOperationException always
845   * @deprecated <b>Pass a parameter of type {@code Comparable} to use {@link
846   *     ImmutableSortedSet#of(Comparable)}.</b>
847   */
848  @DoNotCall("Pass a parameter of type Comparable")
849  @Deprecated
850  public static <E> ImmutableSortedSet<E> of(E e1) {
851    throw new UnsupportedOperationException();
852  }
853
854  /**
855   * Not supported. <b>You are attempting to create a set that may contain a non-{@code Comparable}
856   * element.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
857   * dummy version.
858   *
859   * @throws UnsupportedOperationException always
860   * @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
861   *     ImmutableSortedSet#of(Comparable, Comparable)}.</b>
862   */
863  @DoNotCall("Pass parameters of type Comparable")
864  @Deprecated
865  public static <E> ImmutableSortedSet<E> of(E e1, E e2) {
866    throw new UnsupportedOperationException();
867  }
868
869  /**
870   * Not supported. <b>You are attempting to create a set that may contain a non-{@code Comparable}
871   * element.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
872   * dummy version.
873   *
874   * @throws UnsupportedOperationException always
875   * @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
876   *     ImmutableSortedSet#of(Comparable, Comparable, Comparable)}.</b>
877   */
878  @DoNotCall("Pass parameters of type Comparable")
879  @Deprecated
880  public static <E> ImmutableSortedSet<E> of(E e1, E e2, E e3) {
881    throw new UnsupportedOperationException();
882  }
883
884  /**
885   * Not supported. <b>You are attempting to create a set that may contain a non-{@code Comparable}
886   * element.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
887   * dummy version.
888   *
889   * @throws UnsupportedOperationException always
890   * @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
891   *     ImmutableSortedSet#of(Comparable, Comparable, Comparable, Comparable)}. </b>
892   */
893  @DoNotCall("Pass parameters of type Comparable")
894  @Deprecated
895  public static <E> ImmutableSortedSet<E> of(E e1, E e2, E e3, E e4) {
896    throw new UnsupportedOperationException();
897  }
898
899  /**
900   * Not supported. <b>You are attempting to create a set that may contain a non-{@code Comparable}
901   * element.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
902   * dummy version.
903   *
904   * @throws UnsupportedOperationException always
905   * @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
906   *     ImmutableSortedSet#of( Comparable, Comparable, Comparable, Comparable, Comparable)}. </b>
907   */
908  @DoNotCall("Pass parameters of type Comparable")
909  @Deprecated
910  public static <E> ImmutableSortedSet<E> of(E e1, E e2, E e3, E e4, E e5) {
911    throw new UnsupportedOperationException();
912  }
913
914  /**
915   * Not supported. <b>You are attempting to create a set that may contain a non-{@code Comparable}
916   * element.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
917   * dummy version.
918   *
919   * @throws UnsupportedOperationException always
920   * @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
921   *     ImmutableSortedSet#of(Comparable, Comparable, Comparable, Comparable, Comparable,
922   *     Comparable, Comparable...)}. </b>
923   */
924  @DoNotCall("Pass parameters of type Comparable")
925  @Deprecated
926  public static <E> ImmutableSortedSet<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E... remaining) {
927    throw new UnsupportedOperationException();
928  }
929
930  /**
931   * Not supported. <b>You are attempting to create a set that may contain non-{@code Comparable}
932   * elements.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
933   * dummy version.
934   *
935   * @throws UnsupportedOperationException always
936   * @deprecated <b>Pass parameters of type {@code Comparable} to use {@link
937   *     ImmutableSortedSet#copyOf(Comparable[])}.</b>
938   */
939  @DoNotCall("Pass parameters of type Comparable")
940  @Deprecated
941  // The usage of "Z" here works around bugs in Javadoc (JDK-8318093) and JDiff.
942  public static <Z> ImmutableSortedSet<Z> copyOf(Z[] elements) {
943    throw new UnsupportedOperationException();
944  }
945
946  private static final long serialVersionUID = 0xdecaf;
947}