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