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