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