001/*
002 * Copyright (C) 2008 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.base.Preconditions.checkNotNull;
021import static com.google.common.collect.ObjectArrays.checkElementsNotNull;
022
023import com.google.common.annotations.GwtCompatible;
024import com.google.common.annotations.GwtIncompatible;
025import com.google.errorprone.annotations.CanIgnoreReturnValue;
026import com.google.errorprone.annotations.DoNotCall;
027import com.google.errorprone.annotations.concurrent.LazyInit;
028import java.io.InvalidObjectException;
029import java.io.ObjectInputStream;
030import java.io.Serializable;
031import java.util.Arrays;
032import java.util.Collection;
033import java.util.Collections;
034import java.util.Comparator;
035import java.util.Iterator;
036import java.util.NavigableSet;
037import java.util.SortedSet;
038import javax.annotation.CheckForNull;
039import org.checkerframework.checker.nullness.qual.Nullable;
040
041/**
042 * A {@link NavigableSet} whose contents will never change, with many other important properties
043 * detailed at {@link ImmutableCollection}.
044 *
045 * <p><b>Warning:</b> as with any sorted collection, you are strongly advised not to use a {@link
046 * Comparator} or {@link Comparable} type whose comparison behavior is <i>inconsistent with
047 * equals</i>. That is, {@code a.compareTo(b)} or {@code comparator.compare(a, b)} should equal zero
048 * <i>if and only if</i> {@code a.equals(b)}. If this advice is not followed, the resulting
049 * collection will not correctly obey its specification.
050 *
051 * <p>See the Guava User Guide article on <a href=
052 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>.
053 *
054 * @author Jared Levy
055 * @author Louis Wasserman
056 * @since 2.0 (implements {@code NavigableSet} since 12.0)
057 */
058// TODO(benyu): benchmark and optimize all creation paths, which are a mess now
059@GwtCompatible(serializable = true, emulated = true)
060@SuppressWarnings("serial") // we're overriding default serialization
061@ElementTypesAreNonnullByDefault
062public abstract class ImmutableSortedSet<E> extends ImmutableSortedSetFauxverideShim<E>
063    implements NavigableSet<E>, SortedIterable<E> {
064  static <E> RegularImmutableSortedSet<E> emptySet(Comparator<? super E> comparator) {
065    if (Ordering.natural().equals(comparator)) {
066      return (RegularImmutableSortedSet<E>) RegularImmutableSortedSet.NATURAL_EMPTY_SET;
067    } else {
068      return new RegularImmutableSortedSet<E>(ImmutableList.<E>of(), comparator);
069    }
070  }
071
072  /**
073   * Returns the empty immutable sorted set.
074   *
075   * <p><b>Performance note:</b> the instance returned is a singleton.
076   */
077  public static <E> ImmutableSortedSet<E> of() {
078    return (ImmutableSortedSet<E>) RegularImmutableSortedSet.NATURAL_EMPTY_SET;
079  }
080
081  /** Returns an immutable sorted set containing a single element. */
082  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E element) {
083    return new RegularImmutableSortedSet<E>(ImmutableList.of(element), Ordering.natural());
084  }
085
086  /**
087   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
088   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
089   * one specified is included.
090   *
091   * @throws NullPointerException if any element is null
092   */
093  @SuppressWarnings("unchecked")
094  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E e1, E e2) {
095    return construct(Ordering.natural(), 2, e1, e2);
096  }
097
098  /**
099   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
100   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
101   * one specified is included.
102   *
103   * @throws NullPointerException if any element is null
104   */
105  @SuppressWarnings("unchecked")
106  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E e1, E e2, E e3) {
107    return construct(Ordering.natural(), 3, e1, e2, e3);
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  @SuppressWarnings("unchecked")
118  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E e1, E e2, E e3, E e4) {
119    return construct(Ordering.natural(), 4, e1, e2, e3, e4);
120  }
121
122  /**
123   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
124   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
125   * one specified is included.
126   *
127   * @throws NullPointerException if any element is null
128   */
129  @SuppressWarnings("unchecked")
130  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
131      E e1, E e2, E e3, E e4, E e5) {
132    return construct(Ordering.natural(), 5, e1, e2, e3, e4, e5);
133  }
134
135  /**
136   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
137   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
138   * one specified is included.
139   *
140   * @throws NullPointerException if any element is null
141   * @since 3.0 (source-compatible since 2.0)
142   */
143  @SuppressWarnings("unchecked")
144  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
145      E e1, E e2, E e3, E e4, E e5, E e6, E... remaining) {
146    Comparable[] contents = new Comparable[6 + remaining.length];
147    contents[0] = e1;
148    contents[1] = e2;
149    contents[2] = e3;
150    contents[3] = e4;
151    contents[4] = e5;
152    contents[5] = e6;
153    System.arraycopy(remaining, 0, contents, 6, remaining.length);
154    return construct(Ordering.natural(), contents.length, (E[]) contents);
155  }
156
157  // TODO(kevinb): Consider factory methods that reject duplicates
158
159  /**
160   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
161   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
162   * one specified is included.
163   *
164   * @throws NullPointerException if any of {@code elements} is null
165   * @since 3.0
166   */
167  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> copyOf(E[] elements) {
168    return construct(Ordering.natural(), elements.length, elements.clone());
169  }
170
171  /**
172   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
173   * When multiple elements are equivalent according to {@code compareTo()}, only the first one
174   * specified is included. To create a copy of a {@code SortedSet} that preserves the comparator,
175   * call {@link #copyOfSorted} instead. This method iterates over {@code elements} at most once.
176   *
177   * <p>Note that if {@code s} is a {@code Set<String>}, then {@code ImmutableSortedSet.copyOf(s)}
178   * returns an {@code ImmutableSortedSet<String>} containing each of the strings in {@code s},
179   * while {@code ImmutableSortedSet.of(s)} returns an {@code ImmutableSortedSet<Set<String>>}
180   * containing one element (the given set itself).
181   *
182   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
183   * safe to do so. The exact circumstances under which a copy will or will not be performed are
184   * undocumented and subject to change.
185   *
186   * <p>This method is not type-safe, as it may be called on elements that are not mutually
187   * comparable.
188   *
189   * @throws ClassCastException if the elements are not mutually comparable
190   * @throws NullPointerException if any of {@code elements} is null
191   */
192  public static <E> ImmutableSortedSet<E> copyOf(Iterable<? extends E> elements) {
193    // Hack around E not being a subtype of Comparable.
194    // Unsafe, see ImmutableSortedSetFauxverideShim.
195    @SuppressWarnings("unchecked")
196    Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural();
197    return copyOf(naturalOrder, elements);
198  }
199
200  /**
201   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
202   * When multiple elements are equivalent according to {@code compareTo()}, only the first one
203   * specified is included. To create a copy of a {@code SortedSet} that preserves the comparator,
204   * call {@link #copyOfSorted} instead. This method iterates over {@code elements} at most once.
205   *
206   * <p>Note that if {@code s} is a {@code Set<String>}, then {@code ImmutableSortedSet.copyOf(s)}
207   * returns an {@code ImmutableSortedSet<String>} containing each of the strings in {@code s},
208   * while {@code ImmutableSortedSet.of(s)} returns an {@code ImmutableSortedSet<Set<String>>}
209   * containing one element (the given set itself).
210   *
211   * <p><b>Note:</b> Despite what the method name suggests, if {@code elements} is an {@code
212   * ImmutableSortedSet}, it may be returned instead of a copy.
213   *
214   * <p>This method is not type-safe, as it may be called on elements that are not mutually
215   * comparable.
216   *
217   * <p>This method is safe to use even when {@code elements} is a synchronized or concurrent
218   * collection that is currently being modified by another thread.
219   *
220   * @throws ClassCastException if the elements are not mutually comparable
221   * @throws NullPointerException if any of {@code elements} is null
222   * @since 7.0 (source-compatible since 2.0)
223   */
224  public static <E> ImmutableSortedSet<E> copyOf(Collection<? extends E> elements) {
225    // Hack around E not being a subtype of Comparable.
226    // Unsafe, see ImmutableSortedSetFauxverideShim.
227    @SuppressWarnings("unchecked")
228    Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural();
229    return copyOf(naturalOrder, elements);
230  }
231
232  /**
233   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
234   * When multiple elements are equivalent according to {@code compareTo()}, only the first one
235   * specified is included.
236   *
237   * <p>This method is not type-safe, as it may be called on elements that are not mutually
238   * comparable.
239   *
240   * @throws ClassCastException if the elements are not mutually comparable
241   * @throws NullPointerException if any of {@code elements} is null
242   */
243  public static <E> ImmutableSortedSet<E> copyOf(Iterator<? 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 the given {@code
253   * Comparator}. When multiple elements are equivalent according to {@code compareTo()}, only the
254   * first one specified is included.
255   *
256   * @throws NullPointerException if {@code comparator} or any of {@code elements} is null
257   */
258  public static <E> ImmutableSortedSet<E> copyOf(
259      Comparator<? super E> comparator, Iterator<? extends E> elements) {
260    return new Builder<E>(comparator).addAll(elements).build();
261  }
262
263  /**
264   * Returns an immutable sorted set containing the given elements sorted by the given {@code
265   * Comparator}. When multiple elements are equivalent according to {@code compare()}, only the
266   * first one specified is included. This method iterates over {@code elements} at most once.
267   *
268   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
269   * safe to do so. The exact circumstances under which a copy will or will not be performed are
270   * undocumented and subject to change.
271   *
272   * @throws NullPointerException if {@code comparator} or any of {@code elements} is null
273   */
274  public static <E> ImmutableSortedSet<E> copyOf(
275      Comparator<? super E> comparator, Iterable<? extends E> elements) {
276    checkNotNull(comparator);
277    boolean hasSameComparator = SortedIterables.hasSameComparator(comparator, elements);
278
279    if (hasSameComparator && (elements instanceof ImmutableSortedSet)) {
280      @SuppressWarnings("unchecked")
281      ImmutableSortedSet<E> original = (ImmutableSortedSet<E>) elements;
282      if (!original.isPartialView()) {
283        return original;
284      }
285    }
286    @SuppressWarnings("unchecked") // elements only contains E's; it's safe.
287    E[] array = (E[]) Iterables.toArray(elements);
288    return construct(comparator, array.length, array);
289  }
290
291  /**
292   * Returns an immutable sorted set containing the given elements sorted by the given {@code
293   * Comparator}. When multiple elements are equivalent according to {@code compareTo()}, only the
294   * first one specified is included.
295   *
296   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
297   * safe to do so. The exact circumstances under which a copy will or will not be performed are
298   * undocumented and subject to change.
299   *
300   * <p>This method is safe to use even when {@code elements} is a synchronized or concurrent
301   * collection that is currently being modified by another thread.
302   *
303   * @throws NullPointerException if {@code comparator} or any of {@code elements} is null
304   * @since 7.0 (source-compatible since 2.0)
305   */
306  public static <E> ImmutableSortedSet<E> copyOf(
307      Comparator<? super E> comparator, Collection<? extends E> elements) {
308    return copyOf(comparator, (Iterable<? extends E>) elements);
309  }
310
311  /**
312   * Returns an immutable sorted set containing the elements of a sorted set, sorted by the same
313   * {@code Comparator}. That behavior differs from {@link #copyOf(Iterable)}, which always uses the
314   * natural ordering of the elements.
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 sortedSet} is a synchronized or concurrent
321   * collection that is currently being modified by another thread.
322   *
323   * @throws NullPointerException if {@code sortedSet} or any of its elements is null
324   */
325  public static <E> ImmutableSortedSet<E> copyOfSorted(SortedSet<E> sortedSet) {
326    Comparator<? super E> comparator = SortedIterables.comparator(sortedSet);
327    ImmutableList<E> list = ImmutableList.copyOf(sortedSet);
328    if (list.isEmpty()) {
329      return emptySet(comparator);
330    } else {
331      return new RegularImmutableSortedSet<E>(list, comparator);
332    }
333  }
334
335  /**
336   * Constructs an {@code ImmutableSortedSet} from the first {@code n} elements of {@code contents}.
337   * If {@code k} is the size of the returned {@code ImmutableSortedSet}, then the sorted unique
338   * elements are in the first {@code k} positions of {@code contents}, and {@code contents[i] ==
339   * null} for {@code k <= i < n}.
340   *
341   * <p>This method takes ownership of {@code contents}; do not modify {@code contents} after this
342   * returns.
343   *
344   * @throws NullPointerException if any of the first {@code n} elements of {@code contents} is null
345   */
346  static <E> ImmutableSortedSet<E> construct(
347      Comparator<? super E> comparator, int n, E... contents) {
348    if (n == 0) {
349      return emptySet(comparator);
350    }
351    checkElementsNotNull(contents, n);
352    Arrays.sort(contents, 0, n, comparator);
353    int uniques = 1;
354    for (int i = 1; i < n; i++) {
355      E cur = contents[i];
356      E prev = contents[uniques - 1];
357      if (comparator.compare(cur, prev) != 0) {
358        contents[uniques++] = cur;
359      }
360    }
361    Arrays.fill(contents, uniques, n, null);
362    if (uniques < contents.length / 2) {
363      // Deduplication eliminated many of the elements.  We don't want to retain an arbitrarily
364      // large array relative to the number of elements, so we cap the ratio.
365      contents = Arrays.copyOf(contents, uniques);
366    }
367    return new RegularImmutableSortedSet<E>(
368        ImmutableList.<E>asImmutableList(contents, uniques), comparator);
369  }
370
371  /**
372   * Returns a builder that creates immutable sorted sets with an explicit comparator. If the
373   * comparator has a more general type than the set being generated, such as creating a {@code
374   * SortedSet<Integer>} with a {@code Comparator<Number>}, use the {@link Builder} constructor
375   * instead.
376   *
377   * @throws NullPointerException if {@code comparator} is null
378   */
379  public static <E> Builder<E> orderedBy(Comparator<E> comparator) {
380    return new Builder<E>(comparator);
381  }
382
383  /**
384   * Returns a builder that creates immutable sorted sets whose elements are ordered by the reverse
385   * of their natural ordering.
386   */
387  public static <E extends Comparable<?>> Builder<E> reverseOrder() {
388    return new Builder<E>(Collections.reverseOrder());
389  }
390
391  /**
392   * Returns a builder that creates immutable sorted sets whose elements are ordered by their
393   * natural ordering. The sorted sets use {@link Ordering#natural()} as the comparator. This method
394   * provides more type-safety than {@link #builder}, as it can be called only for classes that
395   * implement {@link Comparable}.
396   */
397  public static <E extends Comparable<?>> Builder<E> naturalOrder() {
398    return new Builder<E>(Ordering.natural());
399  }
400
401  /**
402   * A builder for creating immutable sorted set instances, especially {@code public static final}
403   * sets ("constant sets"), with a given comparator. Example:
404   *
405   * <pre>{@code
406   * public static final ImmutableSortedSet<Number> LUCKY_NUMBERS =
407   *     new ImmutableSortedSet.Builder<Number>(ODDS_FIRST_COMPARATOR)
408   *         .addAll(SINGLE_DIGIT_PRIMES)
409   *         .add(42)
410   *         .build();
411   * }</pre>
412   *
413   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
414   * multiple sets in series. Each set is a superset of the set created before it.
415   *
416   * @since 2.0
417   */
418  public static final class Builder<E> extends ImmutableSet.Builder<E> {
419    private final Comparator<? super E> comparator;
420
421    /**
422     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
423     * ImmutableSortedSet#orderedBy}.
424     */
425    public Builder(Comparator<? super E> comparator) {
426      this.comparator = checkNotNull(comparator);
427    }
428
429    /**
430     * Adds {@code element} to the {@code ImmutableSortedSet}. If the {@code ImmutableSortedSet}
431     * already contains {@code element}, then {@code add} has no effect. (only the previously added
432     * element is retained).
433     *
434     * @param element the element to add
435     * @return this {@code Builder} object
436     * @throws NullPointerException if {@code element} is null
437     */
438    @CanIgnoreReturnValue
439    @Override
440    public Builder<E> add(E element) {
441      super.add(element);
442      return this;
443    }
444
445    /**
446     * Adds each element of {@code elements} to the {@code ImmutableSortedSet}, ignoring duplicate
447     * elements (only the first duplicate element is added).
448     *
449     * @param elements the elements to add
450     * @return this {@code Builder} object
451     * @throws NullPointerException if {@code elements} contains a null element
452     */
453    @CanIgnoreReturnValue
454    @Override
455    public Builder<E> add(E... elements) {
456      super.add(elements);
457      return this;
458    }
459
460    /**
461     * Adds each element of {@code elements} to the {@code ImmutableSortedSet}, ignoring duplicate
462     * elements (only the first duplicate element is added).
463     *
464     * @param elements the elements to add to the {@code ImmutableSortedSet}
465     * @return this {@code Builder} object
466     * @throws NullPointerException if {@code elements} contains a null element
467     */
468    @CanIgnoreReturnValue
469    @Override
470    public Builder<E> addAll(Iterable<? extends E> elements) {
471      super.addAll(elements);
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 to the {@code ImmutableSortedSet}
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> addAll(Iterator<? extends E> elements) {
486      super.addAll(elements);
487      return this;
488    }
489
490    @CanIgnoreReturnValue
491    @Override
492    Builder<E> combine(ImmutableSet.Builder<E> builder) {
493      super.combine(builder);
494      return this;
495    }
496
497    /**
498     * Returns a newly-created {@code ImmutableSortedSet} based on the contents of the {@code
499     * Builder} and its comparator.
500     */
501    @Override
502    public ImmutableSortedSet<E> build() {
503      @SuppressWarnings("unchecked") // we're careful to put only E's in here
504      E[] contentsArray = (E[]) contents;
505      ImmutableSortedSet<E> result = construct(comparator, size, contentsArray);
506      this.size = result.size(); // we eliminated duplicates in-place in contentsArray
507      this.forceCopy = true;
508      return result;
509    }
510  }
511
512  int unsafeCompare(Object a, @CheckForNull Object b) {
513    return unsafeCompare(comparator, a, b);
514  }
515
516  static int unsafeCompare(Comparator<?> comparator, Object a, @CheckForNull Object b) {
517    // Pretend the comparator can compare anything. If it turns out it can't
518    // compare a and b, we should get a CCE or NPE on the subsequent line. Only methods
519    // that are spec'd to throw CCE and NPE should call this.
520    @SuppressWarnings({"unchecked", "nullness"})
521    Comparator<@Nullable Object> unsafeComparator = (Comparator<@Nullable Object>) comparator;
522    return unsafeComparator.compare(a, b);
523  }
524
525  final transient Comparator<? super E> comparator;
526
527  ImmutableSortedSet(Comparator<? super E> comparator) {
528    this.comparator = comparator;
529  }
530
531  /**
532   * Returns the comparator that orders the elements, which is {@link Ordering#natural()} when the
533   * natural ordering of the elements is used. Note that its behavior is not consistent with {@link
534   * SortedSet#comparator()}, which returns {@code null} to indicate natural ordering.
535   */
536  @Override
537  public Comparator<? super E> comparator() {
538    return comparator;
539  }
540
541  @Override // needed to unify the iterator() methods in Collection and SortedIterable
542  public abstract UnmodifiableIterator<E> iterator();
543
544  /**
545   * {@inheritDoc}
546   *
547   * <p>This method returns a serializable {@code ImmutableSortedSet}.
548   *
549   * <p>The {@link SortedSet#headSet} documentation states that a subset of a subset throws an
550   * {@link IllegalArgumentException} if passed a {@code toElement} greater than an earlier {@code
551   * toElement}. However, this method doesn't throw an exception in that situation, but instead
552   * keeps the original {@code toElement}.
553   */
554  @Override
555  public ImmutableSortedSet<E> headSet(E toElement) {
556    return headSet(toElement, false);
557  }
558
559  /** @since 12.0 */
560  @Override
561  public ImmutableSortedSet<E> headSet(E toElement, boolean inclusive) {
562    return headSetImpl(checkNotNull(toElement), inclusive);
563  }
564
565  /**
566   * {@inheritDoc}
567   *
568   * <p>This method returns a serializable {@code ImmutableSortedSet}.
569   *
570   * <p>The {@link SortedSet#subSet} documentation states that a subset of a subset throws an {@link
571   * IllegalArgumentException} if passed a {@code fromElement} smaller than an earlier {@code
572   * fromElement}. However, this method doesn't throw an exception in that situation, but instead
573   * keeps the original {@code fromElement}. Similarly, this method keeps the original {@code
574   * toElement}, instead of throwing an exception, if passed a {@code toElement} greater than an
575   * earlier {@code toElement}.
576   */
577  @Override
578  public ImmutableSortedSet<E> subSet(E fromElement, E toElement) {
579    return subSet(fromElement, true, toElement, false);
580  }
581
582  /** @since 12.0 */
583  @GwtIncompatible // NavigableSet
584  @Override
585  public ImmutableSortedSet<E> subSet(
586      E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
587    checkNotNull(fromElement);
588    checkNotNull(toElement);
589    checkArgument(comparator.compare(fromElement, toElement) <= 0);
590    return subSetImpl(fromElement, fromInclusive, toElement, toInclusive);
591  }
592
593  /**
594   * {@inheritDoc}
595   *
596   * <p>This method returns a serializable {@code ImmutableSortedSet}.
597   *
598   * <p>The {@link SortedSet#tailSet} documentation states that a subset of a subset throws an
599   * {@link IllegalArgumentException} if passed a {@code fromElement} smaller than an earlier {@code
600   * fromElement}. However, this method doesn't throw an exception in that situation, but instead
601   * keeps the original {@code fromElement}.
602   */
603  @Override
604  public ImmutableSortedSet<E> tailSet(E fromElement) {
605    return tailSet(fromElement, true);
606  }
607
608  /** @since 12.0 */
609  @Override
610  public ImmutableSortedSet<E> tailSet(E fromElement, boolean inclusive) {
611    return tailSetImpl(checkNotNull(fromElement), inclusive);
612  }
613
614  /*
615   * These methods perform most headSet, subSet, and tailSet logic, besides
616   * parameter validation.
617   */
618  abstract ImmutableSortedSet<E> headSetImpl(E toElement, boolean inclusive);
619
620  abstract ImmutableSortedSet<E> subSetImpl(
621      E fromElement, boolean fromInclusive, E toElement, boolean toInclusive);
622
623  abstract ImmutableSortedSet<E> tailSetImpl(E fromElement, boolean inclusive);
624
625  /** @since 12.0 */
626  @GwtIncompatible // NavigableSet
627  @Override
628  @CheckForNull
629  public E lower(E e) {
630    return Iterators.getNext(headSet(e, false).descendingIterator(), null);
631  }
632
633  /** @since 12.0 */
634  @Override
635  @CheckForNull
636  public E floor(E e) {
637    return Iterators.getNext(headSet(e, true).descendingIterator(), null);
638  }
639
640  /** @since 12.0 */
641  @Override
642  @CheckForNull
643  public E ceiling(E e) {
644    return Iterables.getFirst(tailSet(e, true), null);
645  }
646
647  /** @since 12.0 */
648  @GwtIncompatible // NavigableSet
649  @Override
650  @CheckForNull
651  public E higher(E e) {
652    return Iterables.getFirst(tailSet(e, false), null);
653  }
654
655  @Override
656  public E first() {
657    return iterator().next();
658  }
659
660  @Override
661  public E last() {
662    return descendingIterator().next();
663  }
664
665  /**
666   * Guaranteed to throw an exception and leave the set unmodified.
667   *
668   * @since 12.0
669   * @throws UnsupportedOperationException always
670   * @deprecated Unsupported operation.
671   */
672  @CanIgnoreReturnValue
673  @Deprecated
674  @GwtIncompatible // NavigableSet
675  @Override
676  @DoNotCall("Always throws UnsupportedOperationException")
677  @CheckForNull
678  public final E pollFirst() {
679    throw new UnsupportedOperationException();
680  }
681
682  /**
683   * Guaranteed to throw an exception and leave the set unmodified.
684   *
685   * @since 12.0
686   * @throws UnsupportedOperationException always
687   * @deprecated Unsupported operation.
688   */
689  @CanIgnoreReturnValue
690  @Deprecated
691  @GwtIncompatible // NavigableSet
692  @Override
693  @DoNotCall("Always throws UnsupportedOperationException")
694  @CheckForNull
695  public final E pollLast() {
696    throw new UnsupportedOperationException();
697  }
698
699  @GwtIncompatible // NavigableSet
700  @LazyInit
701  @CheckForNull
702  transient ImmutableSortedSet<E> descendingSet;
703
704  /** @since 12.0 */
705  @GwtIncompatible // NavigableSet
706  @Override
707  public ImmutableSortedSet<E> descendingSet() {
708    // racy single-check idiom
709    ImmutableSortedSet<E> result = descendingSet;
710    if (result == null) {
711      result = descendingSet = createDescendingSet();
712      result.descendingSet = this;
713    }
714    return result;
715  }
716
717  // Most classes should implement this as new DescendingImmutableSortedSet<E>(this),
718  // but we push down that implementation because ProGuard can't eliminate it even when it's always
719  // overridden.
720  @GwtIncompatible // NavigableSet
721  abstract ImmutableSortedSet<E> createDescendingSet();
722
723  /** @since 12.0 */
724  @GwtIncompatible // NavigableSet
725  @Override
726  public abstract UnmodifiableIterator<E> descendingIterator();
727
728  /** Returns the position of an element within the set, or -1 if not present. */
729  abstract int indexOf(@CheckForNull Object target);
730
731  /*
732   * This class is used to serialize all ImmutableSortedSet instances,
733   * regardless of implementation type. It captures their "logical contents"
734   * only. This is necessary to ensure that the existence of a particular
735   * implementation type is an implementation detail.
736   */
737  private static class SerializedForm<E> implements Serializable {
738    final Comparator<? super E> comparator;
739    final Object[] elements;
740
741    public SerializedForm(Comparator<? super E> comparator, Object[] elements) {
742      this.comparator = comparator;
743      this.elements = elements;
744    }
745
746    @SuppressWarnings("unchecked")
747    Object readResolve() {
748      return new Builder<E>(comparator).add((E[]) elements).build();
749    }
750
751    private static final long serialVersionUID = 0;
752  }
753
754  private void readObject(ObjectInputStream unused) throws InvalidObjectException {
755    throw new InvalidObjectException("Use SerializedForm");
756  }
757
758  @Override
759  Object writeReplace() {
760    return new SerializedForm<E>(comparator, toArray());
761  }
762}