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.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 java.util.Spliterator;
041import java.util.function.Consumer;
042import java.util.function.UnaryOperator;
043import java.util.stream.Collector;
044import org.checkerframework.checker.nullness.compatqual.NullableDecl;
045
046/**
047 * A {@link List} whose contents will never change, with many other important properties detailed at
048 * {@link ImmutableCollection}.
049 *
050 * <p>See the Guava User Guide article on <a href=
051 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained"> immutable collections</a>.
052 *
053 * @see ImmutableMap
054 * @see ImmutableSet
055 * @author Kevin Bourrillion
056 * @since 2.0
057 */
058@GwtCompatible(serializable = true, emulated = true)
059@SuppressWarnings("serial") // we're overriding default serialization
060public abstract class ImmutableList<E> extends ImmutableCollection<E>
061    implements List<E>, RandomAccess {
062
063  /**
064   * Returns a {@code Collector} that accumulates the input elements into a new {@code
065   * ImmutableList}, in encounter order.
066   *
067   * @since 21.0
068   */
069  @Beta
070  public static <E> Collector<E, ?, ImmutableList<E>> toImmutableList() {
071    return CollectCollectors.toImmutableList();
072  }
073
074  /**
075   * Returns the empty immutable list. This list behaves and performs comparably to {@link
076   * Collections#emptyList}, and is preferable mainly for consistency and maintainability of your
077   * code.
078   */
079  // Casting to any type is safe because the list will never hold any elements.
080  @SuppressWarnings("unchecked")
081  public static <E> ImmutableList<E> of() {
082    return (ImmutableList<E>) EMPTY;
083  }
084
085  /**
086   * Returns an immutable list containing a single element. This list behaves and performs
087   * comparably to {@link Collections#singleton}, but will not accept a null element. It is
088   * preferable mainly for consistency and maintainability of your code.
089   *
090   * @throws NullPointerException if {@code element} is null
091   */
092  public static <E> ImmutableList<E> of(E element) {
093    return new SingletonImmutableList<E>(element);
094  }
095
096  /**
097   * Returns an immutable list containing the given elements, in order.
098   *
099   * @throws NullPointerException if any element is null
100   */
101  public static <E> ImmutableList<E> of(E e1, E e2) {
102    return construct(e1, e2);
103  }
104
105  /**
106   * Returns an immutable list containing the given elements, in order.
107   *
108   * @throws NullPointerException if any element is null
109   */
110  public static <E> ImmutableList<E> of(E e1, E e2, E e3) {
111    return construct(e1, e2, e3);
112  }
113
114  /**
115   * Returns an immutable list containing the given elements, in order.
116   *
117   * @throws NullPointerException if any element is null
118   */
119  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4) {
120    return construct(e1, e2, e3, e4);
121  }
122
123  /**
124   * Returns an immutable list containing the given elements, in order.
125   *
126   * @throws NullPointerException if any element is null
127   */
128  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5) {
129    return construct(e1, e2, e3, e4, e5);
130  }
131
132  /**
133   * Returns an immutable list containing the given elements, in order.
134   *
135   * @throws NullPointerException if any element is null
136   */
137  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6) {
138    return construct(e1, e2, e3, e4, e5, e6);
139  }
140
141  /**
142   * Returns an immutable list containing the given elements, in order.
143   *
144   * @throws NullPointerException if any element is null
145   */
146  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7) {
147    return construct(e1, e2, e3, e4, e5, e6, e7);
148  }
149
150  /**
151   * Returns an immutable list containing the given elements, in order.
152   *
153   * @throws NullPointerException if any element is null
154   */
155  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) {
156    return construct(e1, e2, e3, e4, e5, e6, e7, e8);
157  }
158
159  /**
160   * Returns an immutable list containing the given elements, in order.
161   *
162   * @throws NullPointerException if any element is null
163   */
164  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) {
165    return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9);
166  }
167
168  /**
169   * Returns an immutable list containing the given elements, in order.
170   *
171   * @throws NullPointerException if any element is null
172   */
173  public static <E> ImmutableList<E> of(
174      E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) {
175    return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10);
176  }
177
178  /**
179   * Returns an immutable list containing the given elements, in order.
180   *
181   * @throws NullPointerException if any element is null
182   */
183  public static <E> ImmutableList<E> of(
184      E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11) {
185    return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11);
186  }
187
188  // These go up to eleven. After that, you just get the varargs form, and
189  // whatever warnings might come along with it. :(
190
191  /**
192   * Returns an immutable list containing the given elements, in order.
193   *
194   * <p>The array {@code others} must not be longer than {@code Integer.MAX_VALUE - 12}.
195   *
196   * @throws NullPointerException if any element is null
197   * @since 3.0 (source-compatible since 2.0)
198   */
199  @SafeVarargs // For Eclipse. For internal javac we have disabled this pointless type of warning.
200  public static <E> ImmutableList<E> of(
201      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) {
202    checkArgument(
203        others.length <= Integer.MAX_VALUE - 12,
204        "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 any of {@code elements} is null
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 any of {@code elements} is null
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 any of {@code elements} is null
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 any of {@code elements} is null
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(@NullableDecl Object object) {
412    return (object == null) ? -1 : Lists.indexOfImpl(this, object);
413  }
414
415  @Override
416  public int lastIndexOf(@NullableDecl Object object) {
417    return (object == null) ? -1 : Lists.lastIndexOfImpl(this, object);
418  }
419
420  @Override
421  public boolean contains(@NullableDecl 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  public final boolean addAll(int index, Collection<? extends E> newElements) {
497    throw new UnsupportedOperationException();
498  }
499
500  /**
501   * Guaranteed to throw an exception and leave the list unmodified.
502   *
503   * @throws UnsupportedOperationException always
504   * @deprecated Unsupported operation.
505   */
506  @CanIgnoreReturnValue
507  @Deprecated
508  @Override
509  public final E set(int index, E element) {
510    throw new UnsupportedOperationException();
511  }
512
513  /**
514   * Guaranteed to throw an exception and leave the list unmodified.
515   *
516   * @throws UnsupportedOperationException always
517   * @deprecated Unsupported operation.
518   */
519  @Deprecated
520  @Override
521  public final void add(int index, E element) {
522    throw new UnsupportedOperationException();
523  }
524
525  /**
526   * Guaranteed to throw an exception and leave the list unmodified.
527   *
528   * @throws UnsupportedOperationException always
529   * @deprecated Unsupported operation.
530   */
531  @CanIgnoreReturnValue
532  @Deprecated
533  @Override
534  public final E remove(int index) {
535    throw new UnsupportedOperationException();
536  }
537
538  /**
539   * Guaranteed to throw an exception and leave the list unmodified.
540   *
541   * @throws UnsupportedOperationException always
542   * @deprecated Unsupported operation.
543   */
544  @Deprecated
545  @Override
546  public final void replaceAll(UnaryOperator<E> operator) {
547    throw new UnsupportedOperationException();
548  }
549
550  /**
551   * Guaranteed to throw an exception and leave the list unmodified.
552   *
553   * @throws UnsupportedOperationException always
554   * @deprecated Unsupported operation.
555   */
556  @Deprecated
557  @Override
558  public final void sort(Comparator<? super E> c) {
559    throw new UnsupportedOperationException();
560  }
561
562  /**
563   * Returns this list instance.
564   *
565   * @since 2.0
566   */
567  @Override
568  public final ImmutableList<E> asList() {
569    return this;
570  }
571
572  @Override
573  public Spliterator<E> spliterator() {
574    return CollectSpliterators.indexed(size(), SPLITERATOR_CHARACTERISTICS, this::get);
575  }
576
577  @Override
578  int copyIntoArray(Object[] dst, int offset) {
579    // this loop is faster for RandomAccess instances, which ImmutableLists are
580    int size = size();
581    for (int i = 0; i < size; i++) {
582      dst[offset + i] = get(i);
583    }
584    return offset + size;
585  }
586
587  /**
588   * Returns a view of this immutable list in reverse order. For example, {@code ImmutableList.of(1,
589   * 2, 3).reverse()} is equivalent to {@code ImmutableList.of(3, 2, 1)}.
590   *
591   * @return a view of this immutable list in reverse order
592   * @since 7.0
593   */
594  public ImmutableList<E> reverse() {
595    return (size() <= 1) ? this : new ReverseImmutableList<E>(this);
596  }
597
598  private static class ReverseImmutableList<E> extends ImmutableList<E> {
599    private final transient ImmutableList<E> forwardList;
600
601    ReverseImmutableList(ImmutableList<E> backingList) {
602      this.forwardList = backingList;
603    }
604
605    private int reverseIndex(int index) {
606      return (size() - 1) - index;
607    }
608
609    private int reversePosition(int index) {
610      return size() - index;
611    }
612
613    @Override
614    public ImmutableList<E> reverse() {
615      return forwardList;
616    }
617
618    @Override
619    public boolean contains(@NullableDecl Object object) {
620      return forwardList.contains(object);
621    }
622
623    @Override
624    public int indexOf(@NullableDecl Object object) {
625      int index = forwardList.lastIndexOf(object);
626      return (index >= 0) ? reverseIndex(index) : -1;
627    }
628
629    @Override
630    public int lastIndexOf(@NullableDecl Object object) {
631      int index = forwardList.indexOf(object);
632      return (index >= 0) ? reverseIndex(index) : -1;
633    }
634
635    @Override
636    public ImmutableList<E> subList(int fromIndex, int toIndex) {
637      checkPositionIndexes(fromIndex, toIndex, size());
638      return forwardList.subList(reversePosition(toIndex), reversePosition(fromIndex)).reverse();
639    }
640
641    @Override
642    public E get(int index) {
643      checkElementIndex(index, size());
644      return forwardList.get(reverseIndex(index));
645    }
646
647    @Override
648    public int size() {
649      return forwardList.size();
650    }
651
652    @Override
653    boolean isPartialView() {
654      return forwardList.isPartialView();
655    }
656  }
657
658  @Override
659  public boolean equals(@NullableDecl Object obj) {
660    return Lists.equalsImpl(this, obj);
661  }
662
663  @Override
664  public int hashCode() {
665    int hashCode = 1;
666    int n = size();
667    for (int i = 0; i < n; i++) {
668      hashCode = 31 * hashCode + get(i).hashCode();
669
670      hashCode = ~~hashCode;
671      // needed to deal with GWT integer overflow
672    }
673    return hashCode;
674  }
675
676  /*
677   * Serializes ImmutableLists as their logical contents. This ensures that
678   * implementation types do not leak into the serialized representation.
679   */
680  static class SerializedForm implements Serializable {
681    final Object[] elements;
682
683    SerializedForm(Object[] elements) {
684      this.elements = elements;
685    }
686
687    Object readResolve() {
688      return copyOf(elements);
689    }
690
691    private static final long serialVersionUID = 0;
692  }
693
694  private void readObject(ObjectInputStream stream) throws InvalidObjectException {
695    throw new InvalidObjectException("Use SerializedForm");
696  }
697
698  @Override
699  Object writeReplace() {
700    return new SerializedForm(toArray());
701  }
702
703  /**
704   * Returns a new builder. The generated builder is equivalent to the builder created by the {@link
705   * Builder} constructor.
706   */
707  public static <E> Builder<E> builder() {
708    return new Builder<E>();
709  }
710
711  /**
712   * Returns a new builder, expecting the specified number of elements to be added.
713   *
714   * <p>If {@code expectedSize} is exactly the number of elements added to the builder before {@link
715   * Builder#build} is called, the builder is likely to perform better than an unsized {@link
716   * #builder()} would have.
717   *
718   * <p>It is not specified if any performance benefits apply if {@code expectedSize} is close to,
719   * but not exactly, the number of elements added to the builder.
720   *
721   * @since 23.1
722   */
723  @Beta
724  public static <E> Builder<E> builderWithExpectedSize(int expectedSize) {
725    checkNonnegative(expectedSize, "expectedSize");
726    return new ImmutableList.Builder<E>(expectedSize);
727  }
728
729  /**
730   * A builder for creating immutable list instances, especially {@code public static final} lists
731   * ("constant lists"). Example:
732   *
733   * <pre>{@code
734   * public static final ImmutableList<Color> GOOGLE_COLORS
735   *     = new ImmutableList.Builder<Color>()
736   *         .addAll(WEBSAFE_COLORS)
737   *         .add(new Color(0, 191, 255))
738   *         .build();
739   * }</pre>
740   *
741   * <p>Elements appear in the resulting list in the same order they were added to the builder.
742   *
743   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
744   * multiple lists in series. Each new list contains all the elements of the ones created before
745   * it.
746   *
747   * @since 2.0
748   */
749  public static final class Builder<E> extends ImmutableCollection.ArrayBasedBuilder<E> {
750    /**
751     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
752     * ImmutableList#builder}.
753     */
754    public Builder() {
755      this(DEFAULT_INITIAL_CAPACITY);
756    }
757
758    Builder(int capacity) {
759      super(capacity);
760    }
761
762    /**
763     * Adds {@code element} to the {@code ImmutableList}.
764     *
765     * @param element the element to add
766     * @return this {@code Builder} object
767     * @throws NullPointerException if {@code element} is null
768     */
769    @CanIgnoreReturnValue
770    @Override
771    public Builder<E> add(E element) {
772      super.add(element);
773      return this;
774    }
775
776    /**
777     * Adds each element of {@code elements} to the {@code ImmutableList}.
778     *
779     * @param elements the {@code Iterable} to add to the {@code ImmutableList}
780     * @return this {@code Builder} object
781     * @throws NullPointerException if {@code elements} is null or contains a null element
782     */
783    @CanIgnoreReturnValue
784    @Override
785    public Builder<E> addAll(Iterable<? extends E> elements) {
786      super.addAll(elements);
787      return this;
788    }
789
790    /**
791     * Adds each element of {@code elements} to the {@code ImmutableList}.
792     *
793     * @param elements the {@code Iterable} to add to the {@code ImmutableList}
794     * @return this {@code Builder} object
795     * @throws NullPointerException if {@code elements} is null or contains a null element
796     */
797    @CanIgnoreReturnValue
798    @Override
799    public Builder<E> add(E... elements) {
800      super.add(elements);
801      return this;
802    }
803
804    /**
805     * Adds each element of {@code elements} to the {@code ImmutableList}.
806     *
807     * @param elements the {@code Iterable} to add to the {@code ImmutableList}
808     * @return this {@code Builder} object
809     * @throws NullPointerException if {@code elements} is null or contains a null element
810     */
811    @CanIgnoreReturnValue
812    @Override
813    public Builder<E> addAll(Iterator<? extends E> elements) {
814      super.addAll(elements);
815      return this;
816    }
817
818    @CanIgnoreReturnValue
819    @Override
820    Builder<E> combine(ArrayBasedBuilder<E> builder) {
821      super.combine(builder);
822      return this;
823    }
824
825    /**
826     * Returns a newly-created {@code ImmutableList} based on the contents of the {@code Builder}.
827     */
828    @Override
829    public ImmutableList<E> build() {
830      forceCopy = true;
831      return asImmutableList(contents, size);
832    }
833  }
834}