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