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