001/*
002 * Copyright (C) 2007 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.checkElementIndex;
021import static com.google.common.base.Preconditions.checkNotNull;
022import static com.google.common.base.Preconditions.checkPositionIndex;
023import static com.google.common.base.Preconditions.checkPositionIndexes;
024import static com.google.common.collect.CollectPreconditions.checkNonnegative;
025import static com.google.common.collect.ObjectArrays.checkElementsNotNull;
026import static com.google.common.collect.RegularImmutableList.EMPTY;
027
028import com.google.common.annotations.GwtCompatible;
029import com.google.common.annotations.GwtIncompatible;
030import com.google.common.annotations.J2ktIncompatible;
031import com.google.errorprone.annotations.CanIgnoreReturnValue;
032import com.google.errorprone.annotations.DoNotCall;
033import com.google.errorprone.annotations.InlineMe;
034import java.io.InvalidObjectException;
035import java.io.ObjectInputStream;
036import java.io.Serializable;
037import java.util.Arrays;
038import java.util.Collection;
039import java.util.Collections;
040import java.util.Comparator;
041import java.util.Iterator;
042import java.util.List;
043import java.util.RandomAccess;
044import java.util.stream.Collector;
045import javax.annotation.CheckForNull;
046import org.checkerframework.checker.nullness.qual.Nullable;
047
048/**
049 * A {@link List} whose contents will never change, with many other important properties detailed at
050 * {@link ImmutableCollection}.
051 *
052 * <p>See the Guava User Guide article on <a href=
053 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>.
054 *
055 * @see ImmutableMap
056 * @see ImmutableSet
057 * @author Kevin Bourrillion
058 * @since 2.0
059 */
060@GwtCompatible(serializable = true, emulated = true)
061@SuppressWarnings("serial") // we're overriding default serialization
062@ElementTypesAreNonnullByDefault
063public abstract class ImmutableList<E> extends ImmutableCollection<E>
064    implements List<E>, RandomAccess {
065
066  /**
067   * Returns a {@code Collector} that accumulates the input elements into a new {@code
068   * ImmutableList}, in encounter order.
069   *
070   * @since 33.2.0 (available since 21.0 in guava-jre)
071   */
072  @SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"})
073  @IgnoreJRERequirement // Users will use this only if they're already using streams.
074  public static <E> Collector<E, ?, ImmutableList<E>> toImmutableList() {
075    return CollectCollectors.toImmutableList();
076  }
077
078  /**
079   * Returns the empty immutable list. This list behaves and performs comparably to {@link
080   * Collections#emptyList}, and is preferable mainly for consistency and maintainability of your
081   * code.
082   *
083   * <p><b>Performance note:</b> the instance returned is a singleton.
084   */
085  // Casting to any type is safe because the list will never hold any elements.
086  @SuppressWarnings("unchecked")
087  public static <E> ImmutableList<E> of() {
088    return (ImmutableList<E>) EMPTY;
089  }
090
091  /**
092   * Returns an immutable list containing a single element. This list behaves and performs
093   * comparably to {@link Collections#singletonList}, but will not accept a null element. It is
094   * preferable mainly for consistency and maintainability of your code.
095   *
096   * @throws NullPointerException if the element is null
097   */
098  public static <E> ImmutableList<E> of(E e1) {
099    return construct(e1);
100  }
101
102  /**
103   * Returns an immutable list containing the given elements, in order.
104   *
105   * @throws NullPointerException if any element is null
106   */
107  public static <E> ImmutableList<E> of(E e1, E e2) {
108    return construct(e1, e2);
109  }
110
111  /**
112   * Returns an immutable list containing the given elements, in order.
113   *
114   * @throws NullPointerException if any element is null
115   */
116  public static <E> ImmutableList<E> of(E e1, E e2, E e3) {
117    return construct(e1, e2, e3);
118  }
119
120  /**
121   * Returns an immutable list containing the given elements, in order.
122   *
123   * @throws NullPointerException if any element is null
124   */
125  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4) {
126    return construct(e1, e2, e3, e4);
127  }
128
129  /**
130   * Returns an immutable list containing the given elements, in order.
131   *
132   * @throws NullPointerException if any element is null
133   */
134  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5) {
135    return construct(e1, e2, e3, e4, e5);
136  }
137
138  /**
139   * Returns an immutable list containing the given elements, in order.
140   *
141   * @throws NullPointerException if any element is null
142   */
143  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6) {
144    return construct(e1, e2, e3, e4, e5, e6);
145  }
146
147  /**
148   * Returns an immutable list containing the given elements, in order.
149   *
150   * @throws NullPointerException if any element is null
151   */
152  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7) {
153    return construct(e1, e2, e3, e4, e5, e6, e7);
154  }
155
156  /**
157   * Returns an immutable list containing the given elements, in order.
158   *
159   * @throws NullPointerException if any element is null
160   */
161  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) {
162    return construct(e1, e2, e3, e4, e5, e6, e7, e8);
163  }
164
165  /**
166   * Returns an immutable list containing the given elements, in order.
167   *
168   * @throws NullPointerException if any element is null
169   */
170  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) {
171    return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9);
172  }
173
174  /**
175   * Returns an immutable list containing the given elements, in order.
176   *
177   * @throws NullPointerException if any element is null
178   */
179  public static <E> ImmutableList<E> of(
180      E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) {
181    return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10);
182  }
183
184  /**
185   * Returns an immutable list containing the given elements, in order.
186   *
187   * @throws NullPointerException if any element is null
188   */
189  public static <E> ImmutableList<E> of(
190      E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11) {
191    return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11);
192  }
193
194  // These go up to eleven. After that, you just get the varargs form, and
195  // whatever warnings might come along with it. :(
196
197  /**
198   * Returns an immutable list containing the given elements, in order.
199   *
200   * <p>The array {@code others} must not be longer than {@code Integer.MAX_VALUE - 12}.
201   *
202   * @throws NullPointerException if any element is null
203   * @since 3.0 (source-compatible since 2.0)
204   */
205  @SafeVarargs // For Eclipse. For internal javac we have disabled this pointless type of warning.
206  public static <E> ImmutableList<E> of(
207      E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11, E e12, E... others) {
208    checkArgument(
209        others.length <= Integer.MAX_VALUE - 12, "the total number of elements must fit in an int");
210    Object[] array = new Object[12 + others.length];
211    array[0] = e1;
212    array[1] = e2;
213    array[2] = e3;
214    array[3] = e4;
215    array[4] = e5;
216    array[5] = e6;
217    array[6] = e7;
218    array[7] = e8;
219    array[8] = e9;
220    array[9] = e10;
221    array[10] = e11;
222    array[11] = e12;
223    System.arraycopy(others, 0, array, 12, others.length);
224    return construct(array);
225  }
226
227  /**
228   * Returns an immutable list containing the given elements, in order. If {@code elements} is a
229   * {@link Collection}, this method behaves exactly as {@link #copyOf(Collection)}; otherwise, it
230   * behaves exactly as {@code copyOf(elements.iterator()}.
231   *
232   * @throws NullPointerException if {@code elements} contains a null element
233   */
234  public static <E> ImmutableList<E> copyOf(Iterable<? extends E> elements) {
235    checkNotNull(elements); // TODO(kevinb): is this here only for GWT?
236    return (elements instanceof Collection)
237        ? copyOf((Collection<? extends E>) elements)
238        : copyOf(elements.iterator());
239  }
240
241  /**
242   * Returns an immutable list containing the given elements, in order.
243   *
244   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
245   * safe to do so. The exact circumstances under which a copy will or will not be performed are
246   * undocumented and subject to change.
247   *
248   * <p>Note that if {@code list} is a {@code List<String>}, then {@code ImmutableList.copyOf(list)}
249   * returns an {@code ImmutableList<String>} containing each of the strings in {@code list}, while
250   * {@code ImmutableList.of(list)} returns an {@code ImmutableList<List<String>>} containing one
251   * element (the given list itself).
252   *
253   * <p>This method is safe to use even when {@code elements} is a synchronized or concurrent
254   * collection that is currently being modified by another thread.
255   *
256   * @throws NullPointerException if {@code elements} contains a null element
257   */
258  public static <E> ImmutableList<E> copyOf(Collection<? extends E> elements) {
259    if (elements instanceof ImmutableCollection) {
260      @SuppressWarnings("unchecked") // all supported methods are covariant
261      ImmutableList<E> list = ((ImmutableCollection<E>) elements).asList();
262      return list.isPartialView() ? ImmutableList.<E>asImmutableList(list.toArray()) : list;
263    }
264    return construct(elements.toArray());
265  }
266
267  /**
268   * Returns an immutable list containing the given elements, in order.
269   *
270   * @throws NullPointerException if {@code elements} contains a null element
271   */
272  public static <E> ImmutableList<E> copyOf(Iterator<? extends E> elements) {
273    // We special-case for 0 or 1 elements, but going further is madness.
274    if (!elements.hasNext()) {
275      return of();
276    }
277    E first = elements.next();
278    if (!elements.hasNext()) {
279      return of(first);
280    } else {
281      return new ImmutableList.Builder<E>().add(first).addAll(elements).build();
282    }
283  }
284
285  /**
286   * Returns an immutable list containing the given elements, in order.
287   *
288   * @throws NullPointerException if {@code elements} contains a null element
289   * @since 3.0
290   */
291  public static <E> ImmutableList<E> copyOf(E[] elements) {
292    return (elements.length == 0)
293        ? ImmutableList.<E>of()
294        : ImmutableList.<E>construct(elements.clone());
295  }
296
297  /**
298   * Returns an immutable list containing the given elements, sorted according to their natural
299   * order. The sorting algorithm used is stable, so elements that compare as equal will stay in the
300   * order in which they appear in the input.
301   *
302   * <p>If your data has no duplicates, or you wish to deduplicate elements, use {@code
303   * ImmutableSortedSet.copyOf(elements)}; if you want a {@code List} you can use its {@code
304   * asList()} view.
305   *
306   * <p><b>Java 8+ users:</b> If you want to convert a {@link java.util.stream.Stream} to a sorted
307   * {@code ImmutableList}, use {@code stream.sorted().collect(toImmutableList())}.
308   *
309   * @throws NullPointerException if any element in the input is null
310   * @since 21.0
311   */
312  public static <E extends Comparable<? super E>> ImmutableList<E> sortedCopyOf(
313      Iterable<? extends E> elements) {
314    Comparable<?>[] array = Iterables.toArray(elements, new Comparable<?>[0]);
315    checkElementsNotNull((Object[]) array);
316    Arrays.sort(array);
317    return asImmutableList(array);
318  }
319
320  /**
321   * Returns an immutable list containing the given elements, in sorted order relative to the
322   * specified comparator. The sorting algorithm used is stable, so elements that compare as equal
323   * will stay in the order in which they appear in the input.
324   *
325   * <p>If your data has no duplicates, or you wish to deduplicate elements, use {@code
326   * ImmutableSortedSet.copyOf(comparator, elements)}; if you want a {@code List} you can use its
327   * {@code asList()} view.
328   *
329   * <p><b>Java 8+ users:</b> If you want to convert a {@link java.util.stream.Stream} to a sorted
330   * {@code ImmutableList}, use {@code stream.sorted(comparator).collect(toImmutableList())}.
331   *
332   * @throws NullPointerException if any element in the input is null
333   * @since 21.0
334   */
335  public static <E> ImmutableList<E> sortedCopyOf(
336      Comparator<? super E> comparator, Iterable<? extends E> elements) {
337    checkNotNull(comparator);
338    @SuppressWarnings("unchecked") // all supported methods are covariant
339    E[] array = (E[]) Iterables.toArray(elements);
340    checkElementsNotNull(array);
341    Arrays.sort(array, comparator);
342    return asImmutableList(array);
343  }
344
345  /** Views the array as an immutable list. Checks for nulls; does not copy. */
346  private static <E> ImmutableList<E> construct(Object... elements) {
347    return asImmutableList(checkElementsNotNull(elements));
348  }
349
350  /**
351   * Views the array as an immutable list. Does not check for nulls; does not copy.
352   *
353   * <p>The array must be internally created.
354   */
355  static <E> ImmutableList<E> asImmutableList(Object[] elements) {
356    return asImmutableList(elements, elements.length);
357  }
358
359  /** Views the array as an immutable list. Does not check for nulls. */
360  static <E> ImmutableList<E> asImmutableList(@Nullable Object[] elements, int length) {
361    if (length == 0) {
362      return of();
363    }
364    return new RegularImmutableList<E>(elements, length);
365  }
366
367  ImmutableList() {}
368
369  // This declaration is needed to make List.iterator() and
370  // ImmutableCollection.iterator() consistent.
371  @Override
372  public UnmodifiableIterator<E> iterator() {
373    return listIterator();
374  }
375
376  @Override
377  public UnmodifiableListIterator<E> listIterator() {
378    return listIterator(0);
379  }
380
381  @SuppressWarnings("unchecked")
382  @Override
383  public UnmodifiableListIterator<E> listIterator(int index) {
384    checkPositionIndex(index, size());
385    if (isEmpty()) {
386      return (UnmodifiableListIterator<E>) EMPTY_ITR;
387    } else {
388      return new Itr<E>(this, index);
389    }
390  }
391
392  /** A singleton implementation of iterator() for the empty ImmutableList. */
393  private static final UnmodifiableListIterator<Object> EMPTY_ITR =
394      new Itr<Object>(RegularImmutableList.EMPTY, 0);
395
396  static class Itr<E> extends AbstractIndexedListIterator<E> {
397    private final ImmutableList<E> list;
398
399    Itr(ImmutableList<E> list, int index) {
400      super(list.size(), index);
401      this.list = list;
402    }
403
404    @Override
405    protected E get(int index) {
406      return list.get(index);
407    }
408  }
409
410  @Override
411  public int indexOf(@CheckForNull Object object) {
412    return (object == null) ? -1 : Lists.indexOfImpl(this, object);
413  }
414
415  @Override
416  public int lastIndexOf(@CheckForNull Object object) {
417    return (object == null) ? -1 : Lists.lastIndexOfImpl(this, object);
418  }
419
420  @Override
421  public boolean contains(@CheckForNull Object object) {
422    return indexOf(object) >= 0;
423  }
424
425  // constrain the return type to ImmutableList<E>
426
427  /**
428   * Returns an immutable list of the elements between the specified {@code fromIndex}, inclusive,
429   * and {@code toIndex}, exclusive. (If {@code fromIndex} and {@code toIndex} are equal, the empty
430   * immutable list is returned.)
431   *
432   * <p><b>Note:</b> in almost all circumstances, the returned {@link ImmutableList} retains a
433   * strong reference to {@code this}, which may prevent the original list from being garbage
434   * collected. If you want the original list to be eligible for garbage collection, you should
435   * create and use a copy of the sub list (e.g., {@code
436   * ImmutableList.copyOf(originalList.subList(...))}).
437   */
438  @Override
439  public ImmutableList<E> subList(int fromIndex, int toIndex) {
440    checkPositionIndexes(fromIndex, toIndex, size());
441    int length = toIndex - fromIndex;
442    if (length == size()) {
443      return this;
444    } else if (length == 0) {
445      return of();
446    } else {
447      return subListUnchecked(fromIndex, toIndex);
448    }
449  }
450
451  /**
452   * Called by the default implementation of {@link #subList} when {@code toIndex - fromIndex > 1},
453   * after index validation has already been performed.
454   */
455  ImmutableList<E> subListUnchecked(int fromIndex, int toIndex) {
456    return new SubList(fromIndex, toIndex - fromIndex);
457  }
458
459  class SubList extends ImmutableList<E> {
460    final transient int offset;
461    final transient int length;
462
463    SubList(int offset, int length) {
464      this.offset = offset;
465      this.length = length;
466    }
467
468    @Override
469    public int size() {
470      return length;
471    }
472
473    @Override
474    @CheckForNull
475    @Nullable
476    Object[] internalArray() {
477      return ImmutableList.this.internalArray();
478    }
479
480    @Override
481    int internalArrayStart() {
482      return ImmutableList.this.internalArrayStart() + offset;
483    }
484
485    @Override
486    int internalArrayEnd() {
487      return ImmutableList.this.internalArrayStart() + offset + length;
488    }
489
490    @Override
491    public E get(int index) {
492      checkElementIndex(index, length);
493      return ImmutableList.this.get(index + offset);
494    }
495
496    @Override
497    public ImmutableList<E> subList(int fromIndex, int toIndex) {
498      checkPositionIndexes(fromIndex, toIndex, length);
499      return ImmutableList.this.subList(fromIndex + offset, toIndex + offset);
500    }
501
502    @Override
503    boolean isPartialView() {
504      return true;
505    }
506
507    // redeclare to help optimizers with b/310253115
508    @SuppressWarnings("RedundantOverride")
509    @Override
510    @J2ktIncompatible // serialization
511    @GwtIncompatible // serialization
512    Object writeReplace() {
513      return super.writeReplace();
514    }
515  }
516
517  /**
518   * Guaranteed to throw an exception and leave the list unmodified.
519   *
520   * @throws UnsupportedOperationException always
521   * @deprecated Unsupported operation.
522   */
523  @CanIgnoreReturnValue
524  @Deprecated
525  @Override
526  @DoNotCall("Always throws UnsupportedOperationException")
527  public final boolean addAll(int index, Collection<? extends E> newElements) {
528    throw new UnsupportedOperationException();
529  }
530
531  /**
532   * Guaranteed to throw an exception and leave the list unmodified.
533   *
534   * @throws UnsupportedOperationException always
535   * @deprecated Unsupported operation.
536   */
537  @CanIgnoreReturnValue
538  @Deprecated
539  @Override
540  @DoNotCall("Always throws UnsupportedOperationException")
541  public final E set(int index, E element) {
542    throw new UnsupportedOperationException();
543  }
544
545  /**
546   * Guaranteed to throw an exception and leave the list unmodified.
547   *
548   * @throws UnsupportedOperationException always
549   * @deprecated Unsupported operation.
550   */
551  @Deprecated
552  @Override
553  @DoNotCall("Always throws UnsupportedOperationException")
554  public final void add(int index, E element) {
555    throw new UnsupportedOperationException();
556  }
557
558  /**
559   * Guaranteed to throw an exception and leave the list unmodified.
560   *
561   * @throws UnsupportedOperationException always
562   * @deprecated Unsupported operation.
563   */
564  @CanIgnoreReturnValue
565  @Deprecated
566  @Override
567  @DoNotCall("Always throws UnsupportedOperationException")
568  public final E remove(int index) {
569    throw new UnsupportedOperationException();
570  }
571
572  /**
573   * Returns this list instance.
574   *
575   * @since 2.0
576   * @deprecated There is no reason to use this; it always returns {@code this}.
577   */
578  @InlineMe(replacement = "this")
579  @Deprecated
580  @Override
581  public final ImmutableList<E> asList() {
582    return this;
583  }
584
585  @Override
586  int copyIntoArray(@Nullable Object[] dst, int offset) {
587    // this loop is faster for RandomAccess instances, which ImmutableLists are
588    int size = size();
589    for (int i = 0; i < size; i++) {
590      dst[offset + i] = get(i);
591    }
592    return offset + size;
593  }
594
595  /**
596   * Returns a view of this immutable list in reverse order. For example, {@code ImmutableList.of(1,
597   * 2, 3).reverse()} is equivalent to {@code ImmutableList.of(3, 2, 1)}.
598   *
599   * @return a view of this immutable list in reverse order
600   * @since 7.0
601   */
602  public ImmutableList<E> reverse() {
603    return (size() <= 1) ? this : new ReverseImmutableList<E>(this);
604  }
605
606  private static class ReverseImmutableList<E> extends ImmutableList<E> {
607    private final transient ImmutableList<E> forwardList;
608
609    ReverseImmutableList(ImmutableList<E> backingList) {
610      this.forwardList = backingList;
611    }
612
613    private int reverseIndex(int index) {
614      return (size() - 1) - index;
615    }
616
617    private int reversePosition(int index) {
618      return size() - index;
619    }
620
621    @Override
622    public ImmutableList<E> reverse() {
623      return forwardList;
624    }
625
626    @Override
627    public boolean contains(@CheckForNull Object object) {
628      return forwardList.contains(object);
629    }
630
631    @Override
632    public int indexOf(@CheckForNull Object object) {
633      int index = forwardList.lastIndexOf(object);
634      return (index >= 0) ? reverseIndex(index) : -1;
635    }
636
637    @Override
638    public int lastIndexOf(@CheckForNull Object object) {
639      int index = forwardList.indexOf(object);
640      return (index >= 0) ? reverseIndex(index) : -1;
641    }
642
643    @Override
644    public ImmutableList<E> subList(int fromIndex, int toIndex) {
645      checkPositionIndexes(fromIndex, toIndex, size());
646      return forwardList.subList(reversePosition(toIndex), reversePosition(fromIndex)).reverse();
647    }
648
649    @Override
650    public E get(int index) {
651      checkElementIndex(index, size());
652      return forwardList.get(reverseIndex(index));
653    }
654
655    @Override
656    public int size() {
657      return forwardList.size();
658    }
659
660    @Override
661    boolean isPartialView() {
662      return forwardList.isPartialView();
663    }
664
665    // redeclare to help optimizers with b/310253115
666    @SuppressWarnings("RedundantOverride")
667    @Override
668    @J2ktIncompatible // serialization
669    @GwtIncompatible // serialization
670    Object writeReplace() {
671      return super.writeReplace();
672    }
673  }
674
675  @Override
676  public boolean equals(@CheckForNull Object obj) {
677    return Lists.equalsImpl(this, obj);
678  }
679
680  @Override
681  public int hashCode() {
682    int hashCode = 1;
683    int n = size();
684    for (int i = 0; i < n; i++) {
685      hashCode = 31 * hashCode + get(i).hashCode();
686
687      hashCode = ~~hashCode;
688      // needed to deal with GWT integer overflow
689    }
690    return hashCode;
691  }
692
693  /*
694   * Serializes ImmutableLists as their logical contents. This ensures that
695   * implementation types do not leak into the serialized representation.
696   */
697  @J2ktIncompatible // serialization
698  static class SerializedForm implements Serializable {
699    final Object[] elements;
700
701    SerializedForm(Object[] elements) {
702      this.elements = elements;
703    }
704
705    Object readResolve() {
706      return copyOf(elements);
707    }
708
709    private static final long serialVersionUID = 0;
710  }
711
712  @J2ktIncompatible // serialization
713  private void readObject(ObjectInputStream stream) throws InvalidObjectException {
714    throw new InvalidObjectException("Use SerializedForm");
715  }
716
717  @Override
718  @J2ktIncompatible // serialization
719  @GwtIncompatible // serialization
720  Object writeReplace() {
721    return new SerializedForm(toArray());
722  }
723
724  /**
725   * Returns a new builder. The generated builder is equivalent to the builder created by the {@link
726   * Builder} constructor.
727   */
728  public static <E> Builder<E> builder() {
729    return new Builder<>();
730  }
731
732  /**
733   * Returns a new builder, expecting the specified number of elements to be added.
734   *
735   * <p>If {@code expectedSize} is exactly the number of elements added to the builder before {@link
736   * Builder#build} is called, the builder is likely to perform better than an unsized {@link
737   * #builder()} would have.
738   *
739   * <p>It is not specified if any performance benefits apply if {@code expectedSize} is close to,
740   * but not exactly, the number of elements added to the builder.
741   *
742   * @since 23.1
743   */
744  public static <E> Builder<E> builderWithExpectedSize(int expectedSize) {
745    checkNonnegative(expectedSize, "expectedSize");
746    return new ImmutableList.Builder<>(expectedSize);
747  }
748
749  /**
750   * A builder for creating immutable list instances, especially {@code public static final} lists
751   * ("constant lists"). Example:
752   *
753   * <pre>{@code
754   * public static final ImmutableList<Color> GOOGLE_COLORS
755   *     = new ImmutableList.Builder<Color>()
756   *         .addAll(WEBSAFE_COLORS)
757   *         .add(new Color(0, 191, 255))
758   *         .build();
759   * }</pre>
760   *
761   * <p>Elements appear in the resulting list in the same order they were added to the builder.
762   *
763   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
764   * multiple lists in series. Each new list contains all the elements of the ones created before
765   * it.
766   *
767   * @since 2.0
768   */
769  public static final class Builder<E> extends ImmutableCollection.ArrayBasedBuilder<E> {
770    /**
771     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
772     * ImmutableList#builder}.
773     */
774    public Builder() {
775      this(DEFAULT_INITIAL_CAPACITY);
776    }
777
778    Builder(int capacity) {
779      super(capacity);
780    }
781
782    /**
783     * Adds {@code element} to the {@code ImmutableList}.
784     *
785     * @param element the element to add
786     * @return this {@code Builder} object
787     * @throws NullPointerException if {@code element} is null
788     */
789    @CanIgnoreReturnValue
790    @Override
791    public Builder<E> add(E element) {
792      super.add(element);
793      return this;
794    }
795
796    /**
797     * Adds each element of {@code elements} to the {@code ImmutableList}.
798     *
799     * @param elements the {@code Iterable} to add to the {@code ImmutableList}
800     * @return this {@code Builder} object
801     * @throws NullPointerException if {@code elements} is null or contains a null element
802     */
803    @CanIgnoreReturnValue
804    @Override
805    public Builder<E> add(E... elements) {
806      super.add(elements);
807      return this;
808    }
809
810    /**
811     * Adds each element of {@code elements} to the {@code ImmutableList}.
812     *
813     * @param elements the {@code Iterable} to add to the {@code ImmutableList}
814     * @return this {@code Builder} object
815     * @throws NullPointerException if {@code elements} is null or contains a null element
816     */
817    @CanIgnoreReturnValue
818    @Override
819    public Builder<E> addAll(Iterable<? extends E> elements) {
820      super.addAll(elements);
821      return this;
822    }
823
824    /**
825     * Adds each element of {@code elements} to the {@code ImmutableList}.
826     *
827     * @param elements the {@code Iterator} to add to the {@code ImmutableList}
828     * @return this {@code Builder} object
829     * @throws NullPointerException if {@code elements} is null or contains a null element
830     */
831    @CanIgnoreReturnValue
832    @Override
833    public Builder<E> addAll(Iterator<? extends E> elements) {
834      super.addAll(elements);
835      return this;
836    }
837
838    @CanIgnoreReturnValue
839    Builder<E> combine(Builder<E> other) {
840      addAll(other.contents, other.size);
841      return this;
842    }
843
844    /**
845     * Returns a newly-created {@code ImmutableList} based on the contents of the {@code Builder}.
846     */
847    @Override
848    public ImmutableList<E> build() {
849      forceCopy = true;
850      return asImmutableList(contents, size);
851    }
852
853    /**
854     * Returns a newly-created {@code ImmutableList} based on the contents of the {@code Builder},
855     * sorted according to the specified comparator.
856     */
857    @SuppressWarnings("unchecked")
858    ImmutableList<E> buildSorted(Comparator<? super E> comparator) {
859      // Currently only used by ImmutableListMultimap.Builder.orderValuesBy.
860      // In particular, this implies that the comparator can never get "removed," so this can't
861      // invalidate future builds.
862
863      forceCopy = true;
864      Arrays.sort((E[]) contents, 0, size, comparator);
865      return asImmutableList(contents, size);
866    }
867  }
868
869  private static final long serialVersionUID = 0xcafebabe;
870}