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