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