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
065public abstract class ImmutableSortedSet<E> extends ImmutableSet<E>
066    implements NavigableSet<E>, SortedIterable<E> {
067  /**
068   * Returns a {@code Collector} that accumulates the input elements into a new {@code
069   * ImmutableSortedSet}, ordered by the specified comparator.
070   *
071   * <p>If the elements contain duplicates (according to the comparator), only the first duplicate
072   * in encounter order will appear in the result.
073   *
074   * @since 33.2.0 (available since 21.0 in guava-jre)
075   */
076  @SuppressWarnings("Java7ApiChecker")
077  @IgnoreJRERequirement // Users will use this only if they're already using streams.
078  public static <E> Collector<E, ?, ImmutableSortedSet<E>> toImmutableSortedSet(
079      Comparator<? super E> comparator) {
080    return CollectCollectors.toImmutableSortedSet(comparator);
081  }
082
083  static <E> RegularImmutableSortedSet<E> emptySet(Comparator<? super E> comparator) {
084    if (Ordering.natural().equals(comparator)) {
085      @SuppressWarnings("unchecked") // The natural-ordered empty set supports all types.
086      RegularImmutableSortedSet<E> result =
087          (RegularImmutableSortedSet<E>) RegularImmutableSortedSet.NATURAL_EMPTY_SET;
088      return result;
089    } else {
090      return new RegularImmutableSortedSet<>(ImmutableList.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  @SuppressWarnings("unchecked") // The natural-ordered empty set supports all types.
100  public static <E> ImmutableSortedSet<E> of() {
101    return (ImmutableSortedSet<E>) RegularImmutableSortedSet.NATURAL_EMPTY_SET;
102  }
103
104  /** Returns an immutable sorted set containing a single element. */
105  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E e1) {
106    return new RegularImmutableSortedSet<>(ImmutableList.of(e1), Ordering.natural());
107  }
108
109  /**
110   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
111   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
112   * one specified is included.
113   *
114   * @throws NullPointerException if any element is null
115   */
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  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E e1, E e2, E e3) {
128    return construct(Ordering.natural(), 3, e1, e2, e3);
129  }
130
131  /**
132   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
133   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
134   * one specified is included.
135   *
136   * @throws NullPointerException if any element is null
137   */
138  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E e1, E e2, E e3, E e4) {
139    return construct(Ordering.natural(), 4, e1, e2, e3, e4);
140  }
141
142  /**
143   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
144   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
145   * one specified is included.
146   *
147   * @throws NullPointerException if any element is null
148   */
149  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
150      E e1, E e2, E e3, E e4, E e5) {
151    return construct(Ordering.natural(), 5, e1, e2, e3, e4, e5);
152  }
153
154  /**
155   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
156   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
157   * one specified is included.
158   *
159   * @throws NullPointerException if any element is null
160   * @since 3.0 (source-compatible since 2.0)
161   */
162  @SuppressWarnings("unchecked")
163  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
164      E e1, E e2, E e3, E e4, E e5, E e6, E... remaining) {
165    Comparable<?>[] contents = new Comparable<?>[6 + remaining.length];
166    contents[0] = e1;
167    contents[1] = e2;
168    contents[2] = e3;
169    contents[3] = e4;
170    contents[4] = e5;
171    contents[5] = e6;
172    arraycopy(remaining, 0, contents, 6, remaining.length);
173    return construct(Ordering.natural(), contents.length, (E[]) contents);
174  }
175
176  // TODO(kevinb): Consider factory methods that reject duplicates
177
178  /**
179   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
180   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
181   * one specified is included.
182   *
183   * @throws NullPointerException if any of {@code elements} is null
184   * @since 3.0
185   */
186  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> copyOf(E[] elements) {
187    return construct(Ordering.natural(), elements.length, elements.clone());
188  }
189
190  /**
191   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
192   * When multiple elements are equivalent according to {@code compareTo()}, only the first one
193   * specified is included. To create a copy of a {@code SortedSet} that preserves the comparator,
194   * call {@link #copyOfSorted} instead. This method iterates over {@code elements} at most once.
195   *
196   * <p>Note that if {@code s} is a {@code Set<String>}, then {@code ImmutableSortedSet.copyOf(s)}
197   * returns an {@code ImmutableSortedSet<String>} containing each of the strings in {@code s},
198   * while {@code ImmutableSortedSet.of(s)} returns an {@code ImmutableSortedSet<Set<String>>}
199   * containing one element (the given set itself).
200   *
201   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
202   * safe to do so. The exact circumstances under which a copy will or will not be performed are
203   * undocumented and subject to change.
204   *
205   * <p>This method is not type-safe, as it may be called on elements that are not mutually
206   * comparable.
207   *
208   * @throws ClassCastException if the elements are not mutually comparable
209   * @throws NullPointerException if any of {@code elements} is null
210   */
211  public static <E> ImmutableSortedSet<E> copyOf(Iterable<? extends E> elements) {
212    // Hack around E not being a subtype of Comparable.
213    // Unsafe, see ImmutableSortedSetFauxverideShim.
214    @SuppressWarnings("unchecked")
215    Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable<?>>natural();
216    return copyOf(naturalOrder, elements);
217  }
218
219  /**
220   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
221   * When multiple elements are equivalent according to {@code compareTo()}, only the first one
222   * specified is included. To create a copy of a {@code SortedSet} that preserves the comparator,
223   * call {@link #copyOfSorted} instead. This method iterates over {@code elements} at most once.
224   *
225   * <p>Note that if {@code s} is a {@code Set<String>}, then {@code ImmutableSortedSet.copyOf(s)}
226   * returns an {@code ImmutableSortedSet<String>} containing each of the strings in {@code s},
227   * while {@code ImmutableSortedSet.of(s)} returns an {@code ImmutableSortedSet<Set<String>>}
228   * containing one element (the given set itself).
229   *
230   * <p><b>Note:</b> Despite what the method name suggests, if {@code elements} is an {@code
231   * ImmutableSortedSet}, it may be returned instead of a copy.
232   *
233   * <p>This method is not type-safe, as it may be called on elements that are not mutually
234   * comparable.
235   *
236   * <p>This method is safe to use even when {@code elements} is a synchronized or concurrent
237   * collection that is currently being modified by another thread.
238   *
239   * @throws ClassCastException if the elements are not mutually comparable
240   * @throws NullPointerException if any of {@code elements} is null
241   * @since 7.0 (source-compatible since 2.0)
242   */
243  public static <E> ImmutableSortedSet<E> copyOf(Collection<? extends E> elements) {
244    // Hack around E not being a subtype of Comparable.
245    // Unsafe, see ImmutableSortedSetFauxverideShim.
246    @SuppressWarnings("unchecked")
247    Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable<?>>natural();
248    return copyOf(naturalOrder, elements);
249  }
250
251  /**
252   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
253   * When multiple elements are equivalent according to {@code compareTo()}, only the first one
254   * specified is included.
255   *
256   * <p>This method is not type-safe, as it may be called on elements that are not mutually
257   * comparable.
258   *
259   * @throws ClassCastException if the elements are not mutually comparable
260   * @throws NullPointerException if any of {@code elements} is null
261   */
262  public static <E> ImmutableSortedSet<E> copyOf(Iterator<? extends E> elements) {
263    // Hack around E not being a subtype of Comparable.
264    // Unsafe, see ImmutableSortedSetFauxverideShim.
265    @SuppressWarnings("unchecked")
266    Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable<?>>natural();
267    return copyOf(naturalOrder, elements);
268  }
269
270  /**
271   * Returns an immutable sorted set containing the given elements sorted by the given {@code
272   * Comparator}. When multiple elements are equivalent according to {@code compareTo()}, only the
273   * first one specified is included.
274   *
275   * @throws NullPointerException if {@code comparator} or any of {@code elements} is null
276   */
277  public static <E> ImmutableSortedSet<E> copyOf(
278      Comparator<? super E> comparator, Iterator<? extends E> elements) {
279    return new Builder<E>(comparator).addAll(elements).build();
280  }
281
282  /**
283   * Returns an immutable sorted set containing the given elements sorted by the given {@code
284   * Comparator}. When multiple elements are equivalent according to {@code compare()}, only the
285   * first one specified is included. This method iterates over {@code elements} at most once.
286   *
287   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
288   * safe to do so. The exact circumstances under which a copy will or will not be performed are
289   * undocumented and subject to change.
290   *
291   * @throws NullPointerException if {@code comparator} or any of {@code elements} is null
292   */
293  public static <E> ImmutableSortedSet<E> copyOf(
294      Comparator<? super E> comparator, Iterable<? extends E> elements) {
295    checkNotNull(comparator);
296    boolean hasSameComparator = SortedIterables.hasSameComparator(comparator, elements);
297
298    if (hasSameComparator && (elements instanceof ImmutableSortedSet)) {
299      @SuppressWarnings("unchecked")
300      ImmutableSortedSet<E> original = (ImmutableSortedSet<E>) elements;
301      if (!original.isPartialView()) {
302        return original;
303      }
304    }
305    @SuppressWarnings("unchecked") // elements only contains E's; it's safe.
306    E[] array = (E[]) Iterables.toArray(elements);
307    return construct(comparator, array.length, array);
308  }
309
310  /**
311   * Returns an immutable sorted set containing the given elements sorted by the given {@code
312   * Comparator}. When multiple elements are equivalent according to {@code compareTo()}, only the
313   * first one specified is included.
314   *
315   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
316   * safe to do so. The exact circumstances under which a copy will or will not be performed are
317   * undocumented and subject to change.
318   *
319   * <p>This method is safe to use even when {@code elements} is a synchronized or concurrent
320   * collection that is currently being modified by another thread.
321   *
322   * @throws NullPointerException if {@code comparator} or any of {@code elements} is null
323   * @since 7.0 (source-compatible since 2.0)
324   */
325  public static <E> ImmutableSortedSet<E> copyOf(
326      Comparator<? super E> comparator, Collection<? extends E> elements) {
327    return copyOf(comparator, (Iterable<? extends E>) elements);
328  }
329
330  /**
331   * Returns an immutable sorted set containing the elements of a sorted set, sorted by the same
332   * {@code Comparator}. That behavior differs from {@link #copyOf(Iterable)}, which always uses the
333   * natural ordering of the elements.
334   *
335   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
336   * safe to do so. The exact circumstances under which a copy will or will not be performed are
337   * undocumented and subject to change.
338   *
339   * <p>This method is safe to use even when {@code sortedSet} is a synchronized or concurrent
340   * collection that is currently being modified by another thread.
341   *
342   * @throws NullPointerException if {@code sortedSet} or any of its elements is null
343   */
344  public static <E> ImmutableSortedSet<E> copyOfSorted(SortedSet<E> sortedSet) {
345    Comparator<? super E> comparator = SortedIterables.comparator(sortedSet);
346    ImmutableList<E> list = ImmutableList.copyOf(sortedSet);
347    if (list.isEmpty()) {
348      return emptySet(comparator);
349    } else {
350      return new RegularImmutableSortedSet<>(list, comparator);
351    }
352  }
353
354  /**
355   * Constructs an {@code ImmutableSortedSet} from the first {@code n} elements of {@code contents}.
356   * If {@code k} is the size of the returned {@code ImmutableSortedSet}, then the sorted unique
357   * elements are in the first {@code k} positions of {@code contents}, and {@code contents[i] ==
358   * null} for {@code k <= i < n}.
359   *
360   * <p>This method takes ownership of {@code contents}; do not modify {@code contents} after this
361   * returns.
362   *
363   * @throws NullPointerException if any of the first {@code n} elements of {@code contents} is null
364   */
365  static <E> ImmutableSortedSet<E> construct(
366      Comparator<? super E> comparator, int n, E... contents) {
367    if (n == 0) {
368      return emptySet(comparator);
369    }
370    checkElementsNotNull(contents, n);
371    sort(contents, 0, n, comparator);
372    int uniques = 1;
373    for (int i = 1; i < n; i++) {
374      E cur = contents[i];
375      E prev = contents[uniques - 1];
376      if (comparator.compare(cur, prev) != 0) {
377        contents[uniques++] = cur;
378      }
379    }
380    Arrays.fill(contents, uniques, n, null);
381    if (uniques < contents.length / 2) {
382      // Deduplication eliminated many of the elements.  We don't want to retain an arbitrarily
383      // large array relative to the number of elements, so we cap the ratio.
384      contents = Arrays.copyOf(contents, uniques);
385    }
386    return new RegularImmutableSortedSet<E>(
387        ImmutableList.<E>asImmutableList(contents, uniques), comparator);
388  }
389
390  /**
391   * Returns a builder that creates immutable sorted sets with an explicit comparator. If the
392   * comparator has a more general type than the set being generated, such as creating a {@code
393   * SortedSet<Integer>} with a {@code Comparator<Number>}, use the {@link Builder} constructor
394   * instead.
395   *
396   * @throws NullPointerException if {@code comparator} is null
397   */
398  public static <E> Builder<E> orderedBy(Comparator<E> comparator) {
399    return new Builder<>(comparator);
400  }
401
402  /**
403   * Returns a builder that creates immutable sorted sets whose elements are ordered by the reverse
404   * of their natural ordering.
405   */
406  public static <E extends Comparable<?>> Builder<E> reverseOrder() {
407    return new Builder<>(Collections.reverseOrder());
408  }
409
410  /**
411   * Returns a builder that creates immutable sorted sets whose elements are ordered by their
412   * natural ordering. The sorted sets use {@link Ordering#natural()} as the comparator. This method
413   * provides more type-safety than {@link #builder}, as it can be called only for classes that
414   * implement {@link Comparable}.
415   */
416  public static <E extends Comparable<?>> Builder<E> naturalOrder() {
417    return new Builder<>(Ordering.natural());
418  }
419
420  /**
421   * A builder for creating immutable sorted set instances, especially {@code public static final}
422   * sets ("constant sets"), with a given comparator. Example:
423   *
424   * <pre>{@code
425   * public static final ImmutableSortedSet<Number> LUCKY_NUMBERS =
426   *     new ImmutableSortedSet.Builder<Number>(ODDS_FIRST_COMPARATOR)
427   *         .addAll(SINGLE_DIGIT_PRIMES)
428   *         .add(42)
429   *         .build();
430   * }</pre>
431   *
432   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
433   * multiple sets in series. Each set is a superset of the set created before it.
434   *
435   * @since 2.0
436   */
437  public static final class Builder<E> extends ImmutableSet.Builder<E> {
438    private final Comparator<? super E> comparator;
439
440    /**
441     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
442     * ImmutableSortedSet#orderedBy}.
443     */
444    /*
445     * TODO(cpovirk): use Object[] instead of E[] in the mainline? (The backport is different and
446     * doesn't need this suppression, but we keep it to minimize diffs.) Generally be more clear
447     * about when we have an Object[] vs. a Comparable[] or other array type in internalArray? If we
448     * used Object[], we might be able to optimize toArray() to use clone() sometimes. (See
449     * cl/592273615 and cl/592273683.)
450     */
451    public Builder(Comparator<? super E> comparator) {
452      this.comparator = checkNotNull(comparator);
453    }
454
455    Builder(Comparator<? super E> comparator, int expectedKeys) {
456      super(expectedKeys, false);
457      this.comparator = checkNotNull(comparator);
458    }
459
460    /**
461     * Adds {@code element} to the {@code ImmutableSortedSet}. If the {@code ImmutableSortedSet}
462     * already contains {@code element}, then {@code add} has no effect. (only the previously added
463     * element is retained).
464     *
465     * @param element the element to add
466     * @return this {@code Builder} object
467     * @throws NullPointerException if {@code element} is null
468     */
469    @CanIgnoreReturnValue
470    @Override
471    public Builder<E> add(E element) {
472      super.add(element);
473      return this;
474    }
475
476    /**
477     * Adds each element of {@code elements} to the {@code ImmutableSortedSet}, ignoring duplicate
478     * elements (only the first duplicate element is added).
479     *
480     * @param elements the elements to add
481     * @return this {@code Builder} object
482     * @throws NullPointerException if {@code elements} contains a null element
483     */
484    @CanIgnoreReturnValue
485    @Override
486    public Builder<E> add(E... elements) {
487      super.add(elements);
488      return this;
489    }
490
491    /**
492     * Adds each element of {@code elements} to the {@code ImmutableSortedSet}, ignoring duplicate
493     * elements (only the first duplicate element is added).
494     *
495     * @param elements the elements to add to the {@code ImmutableSortedSet}
496     * @return this {@code Builder} object
497     * @throws NullPointerException if {@code elements} contains a null element
498     */
499    @CanIgnoreReturnValue
500    @Override
501    public Builder<E> addAll(Iterable<? extends E> elements) {
502      super.addAll(elements);
503      return this;
504    }
505
506    /**
507     * Adds each element of {@code elements} to the {@code ImmutableSortedSet}, ignoring duplicate
508     * elements (only the first duplicate element is added).
509     *
510     * @param elements the elements to add to the {@code ImmutableSortedSet}
511     * @return this {@code Builder} object
512     * @throws NullPointerException if {@code elements} contains a null element
513     */
514    @CanIgnoreReturnValue
515    @Override
516    public Builder<E> addAll(Iterator<? extends E> elements) {
517      super.addAll(elements);
518      return this;
519    }
520
521    @CanIgnoreReturnValue
522    @Override
523    Builder<E> combine(ImmutableSet.Builder<E> builder) {
524      super.combine(builder);
525      return this;
526    }
527
528    /**
529     * Returns a newly-created {@code ImmutableSortedSet} based on the contents of the {@code
530     * Builder} and its comparator.
531     */
532    @Override
533    public ImmutableSortedSet<E> build() {
534      @SuppressWarnings("unchecked") // we're careful to put only E's in here
535      E[] contentsArray = (E[]) contents;
536      ImmutableSortedSet<E> result = construct(comparator, size, contentsArray);
537      this.size = result.size(); // we eliminated duplicates in-place in contentsArray
538      this.forceCopy = true;
539      return result;
540    }
541  }
542
543  int unsafeCompare(Object a, @CheckForNull Object b) {
544    return unsafeCompare(comparator, a, b);
545  }
546
547  static int unsafeCompare(Comparator<?> comparator, Object a, @CheckForNull Object b) {
548    // Pretend the comparator can compare anything. If it turns out it can't
549    // compare a and b, we should get a CCE or NPE on the subsequent line. Only methods
550    // that are spec'd to throw CCE and NPE should call this.
551    @SuppressWarnings({"unchecked", "nullness"})
552    Comparator<@Nullable Object> unsafeComparator = (Comparator<@Nullable Object>) comparator;
553    return unsafeComparator.compare(a, b);
554  }
555
556  final transient Comparator<? super E> comparator;
557
558  ImmutableSortedSet(Comparator<? super E> comparator) {
559    this.comparator = comparator;
560  }
561
562  /**
563   * Returns the comparator that orders the elements, which is {@link Ordering#natural()} when the
564   * natural ordering of the elements is used. Note that its behavior is not consistent with {@link
565   * SortedSet#comparator()}, which returns {@code null} to indicate natural ordering.
566   */
567  @Override
568  public Comparator<? super E> comparator() {
569    return comparator;
570  }
571
572  @Override // needed to unify the iterator() methods in Collection and SortedIterable
573  public abstract UnmodifiableIterator<E> iterator();
574
575  /**
576   * {@inheritDoc}
577   *
578   * <p>This method returns a serializable {@code ImmutableSortedSet}.
579   *
580   * <p>The {@link SortedSet#headSet} documentation states that a subset of a subset throws an
581   * {@link IllegalArgumentException} if passed a {@code toElement} greater than an earlier {@code
582   * toElement}. However, this method doesn't throw an exception in that situation, but instead
583   * keeps the original {@code toElement}.
584   */
585  @Override
586  public ImmutableSortedSet<E> headSet(E toElement) {
587    return headSet(toElement, false);
588  }
589
590  /** @since 12.0 */
591  @Override
592  public ImmutableSortedSet<E> headSet(E toElement, boolean inclusive) {
593    return headSetImpl(checkNotNull(toElement), inclusive);
594  }
595
596  /**
597   * {@inheritDoc}
598   *
599   * <p>This method returns a serializable {@code ImmutableSortedSet}.
600   *
601   * <p>The {@link SortedSet#subSet} documentation states that a subset of a subset throws an {@link
602   * IllegalArgumentException} if passed a {@code fromElement} smaller than an earlier {@code
603   * fromElement}. However, this method doesn't throw an exception in that situation, but instead
604   * keeps the original {@code fromElement}. Similarly, this method keeps the original {@code
605   * toElement}, instead of throwing an exception, if passed a {@code toElement} greater than an
606   * earlier {@code toElement}.
607   */
608  @Override
609  public ImmutableSortedSet<E> subSet(E fromElement, E toElement) {
610    return subSet(fromElement, true, toElement, false);
611  }
612
613  /** @since 12.0 */
614  @GwtIncompatible // NavigableSet
615  @Override
616  public ImmutableSortedSet<E> subSet(
617      E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
618    checkNotNull(fromElement);
619    checkNotNull(toElement);
620    checkArgument(comparator.compare(fromElement, toElement) <= 0);
621    return subSetImpl(fromElement, fromInclusive, toElement, toInclusive);
622  }
623
624  /**
625   * {@inheritDoc}
626   *
627   * <p>This method returns a serializable {@code ImmutableSortedSet}.
628   *
629   * <p>The {@link SortedSet#tailSet} documentation states that a subset of a subset throws an
630   * {@link IllegalArgumentException} if passed a {@code fromElement} smaller than an earlier {@code
631   * fromElement}. However, this method doesn't throw an exception in that situation, but instead
632   * keeps the original {@code fromElement}.
633   */
634  @Override
635  public ImmutableSortedSet<E> tailSet(E fromElement) {
636    return tailSet(fromElement, true);
637  }
638
639  /** @since 12.0 */
640  @Override
641  public ImmutableSortedSet<E> tailSet(E fromElement, boolean inclusive) {
642    return tailSetImpl(checkNotNull(fromElement), inclusive);
643  }
644
645  /*
646   * These methods perform most headSet, subSet, and tailSet logic, besides
647   * parameter validation.
648   */
649  abstract ImmutableSortedSet<E> headSetImpl(E toElement, boolean inclusive);
650
651  abstract ImmutableSortedSet<E> subSetImpl(
652      E fromElement, boolean fromInclusive, E toElement, boolean toInclusive);
653
654  abstract ImmutableSortedSet<E> tailSetImpl(E fromElement, boolean inclusive);
655
656  /** @since 12.0 */
657  @GwtIncompatible // NavigableSet
658  @Override
659  @CheckForNull
660  public E lower(E e) {
661    return Iterators.<@Nullable E>getNext(headSet(e, false).descendingIterator(), null);
662  }
663
664  /** @since 12.0 */
665  @Override
666  @CheckForNull
667  public E floor(E e) {
668    return Iterators.<@Nullable E>getNext(headSet(e, true).descendingIterator(), null);
669  }
670
671  /** @since 12.0 */
672  @Override
673  @CheckForNull
674  public E ceiling(E e) {
675    return Iterables.<@Nullable E>getFirst(tailSet(e, true), null);
676  }
677
678  /** @since 12.0 */
679  @GwtIncompatible // NavigableSet
680  @Override
681  @CheckForNull
682  public E higher(E e) {
683    return Iterables.<@Nullable E>getFirst(tailSet(e, false), null);
684  }
685
686  @Override
687  public E first() {
688    return iterator().next();
689  }
690
691  @Override
692  public E last() {
693    return descendingIterator().next();
694  }
695
696  /**
697   * Guaranteed to throw an exception and leave the set unmodified.
698   *
699   * @since 12.0
700   * @throws UnsupportedOperationException always
701   * @deprecated Unsupported operation.
702   */
703  @CanIgnoreReturnValue
704  @Deprecated
705  @GwtIncompatible // NavigableSet
706  @Override
707  @DoNotCall("Always throws UnsupportedOperationException")
708  @CheckForNull
709  public final E pollFirst() {
710    throw new UnsupportedOperationException();
711  }
712
713  /**
714   * Guaranteed to throw an exception and leave the set unmodified.
715   *
716   * @since 12.0
717   * @throws UnsupportedOperationException always
718   * @deprecated Unsupported operation.
719   */
720  @CanIgnoreReturnValue
721  @Deprecated
722  @GwtIncompatible // NavigableSet
723  @Override
724  @DoNotCall("Always throws UnsupportedOperationException")
725  @CheckForNull
726  public final E pollLast() {
727    throw new UnsupportedOperationException();
728  }
729
730  @GwtIncompatible // NavigableSet
731  @LazyInit
732  @CheckForNull
733  transient 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(@CheckForNull 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}