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