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