001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.base.Preconditions.checkElementIndex;
021import static com.google.common.base.Preconditions.checkNotNull;
022import static com.google.common.base.Preconditions.checkPositionIndex;
023import static com.google.common.base.Preconditions.checkPositionIndexes;
024import static com.google.common.collect.CollectPreconditions.checkNonnegative;
025import static com.google.common.collect.ObjectArrays.checkElementsNotNull;
026import static com.google.common.collect.RegularImmutableList.EMPTY;
027
028import com.google.common.annotations.GwtCompatible;
029import com.google.common.annotations.J2ktIncompatible;
030import com.google.errorprone.annotations.CanIgnoreReturnValue;
031import com.google.errorprone.annotations.DoNotCall;
032import com.google.errorprone.annotations.InlineMe;
033import java.io.InvalidObjectException;
034import java.io.ObjectInputStream;
035import java.io.Serializable;
036import java.util.Arrays;
037import java.util.Collection;
038import java.util.Collections;
039import java.util.Comparator;
040import java.util.Iterator;
041import java.util.List;
042import java.util.RandomAccess;
043import javax.annotation.CheckForNull;
044import org.checkerframework.checker.nullness.qual.Nullable;
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
060@ElementTypesAreNonnullByDefault
061public abstract class ImmutableList<E> extends ImmutableCollection<E>
062    implements List<E>, RandomAccess {
063  /**
064   * Returns the empty immutable list. This list behaves and performs comparably to {@link
065   * Collections#emptyList}, and is preferable mainly for consistency and maintainability of your
066   * code.
067   *
068   * <p><b>Performance note:</b> the instance returned is a singleton.
069   */
070  // Casting to any type is safe because the list will never hold any elements.
071  @SuppressWarnings("unchecked")
072  public static <E> ImmutableList<E> of() {
073    return (ImmutableList<E>) EMPTY;
074  }
075
076  /**
077   * Returns an immutable list containing a single element. This list behaves and performs
078   * comparably to {@link Collections#singletonList}, but will not accept a null element. It is
079   * preferable mainly for consistency and maintainability of your code.
080   *
081   * @throws NullPointerException if {@code element} is null
082   */
083  public static <E> ImmutableList<E> of(E element) {
084    return construct(element);
085  }
086
087  /**
088   * Returns an immutable list containing the given elements, in order.
089   *
090   * @throws NullPointerException if any element is null
091   */
092  public static <E> ImmutableList<E> of(E e1, E e2) {
093    return construct(e1, e2);
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, E e3) {
102    return construct(e1, e2, e3);
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, E e4) {
111    return construct(e1, e2, e3, e4);
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, E e5) {
120    return construct(e1, e2, e3, e4, e5);
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, E e6) {
129    return construct(e1, e2, e3, e4, e5, e6);
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, E e7) {
138    return construct(e1, e2, e3, e4, e5, e6, e7);
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, E e8) {
147    return construct(e1, e2, e3, e4, e5, e6, e7, e8);
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, E e9) {
156    return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9);
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(
165      E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) {
166    return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10);
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, E e11) {
176    return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11);
177  }
178
179  // These go up to eleven. After that, you just get the varargs form, and
180  // whatever warnings might come along with it. :(
181
182  /**
183   * Returns an immutable list containing the given elements, in order.
184   *
185   * <p>The array {@code others} must not be longer than {@code Integer.MAX_VALUE - 12}.
186   *
187   * @throws NullPointerException if any element is null
188   * @since 3.0 (source-compatible since 2.0)
189   */
190  @SafeVarargs // For Eclipse. For internal javac we have disabled this pointless type of warning.
191  public static <E> ImmutableList<E> of(
192      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) {
193    checkArgument(
194        others.length <= Integer.MAX_VALUE - 12, "the total number of elements must fit in an int");
195    Object[] array = new Object[12 + others.length];
196    array[0] = e1;
197    array[1] = e2;
198    array[2] = e3;
199    array[3] = e4;
200    array[4] = e5;
201    array[5] = e6;
202    array[6] = e7;
203    array[7] = e8;
204    array[8] = e9;
205    array[9] = e10;
206    array[10] = e11;
207    array[11] = e12;
208    System.arraycopy(others, 0, array, 12, others.length);
209    return construct(array);
210  }
211
212  /**
213   * Returns an immutable list containing the given elements, in order. If {@code elements} is a
214   * {@link Collection}, this method behaves exactly as {@link #copyOf(Collection)}; otherwise, it
215   * behaves exactly as {@code copyOf(elements.iterator()}.
216   *
217   * @throws NullPointerException if {@code elements} contains a null element
218   */
219  public static <E> ImmutableList<E> copyOf(Iterable<? extends E> elements) {
220    checkNotNull(elements); // TODO(kevinb): is this here only for GWT?
221    return (elements instanceof Collection)
222        ? copyOf((Collection<? extends E>) elements)
223        : copyOf(elements.iterator());
224  }
225
226  /**
227   * Returns an immutable list containing the given elements, in order.
228   *
229   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
230   * safe to do so. The exact circumstances under which a copy will or will not be performed are
231   * undocumented and subject to change.
232   *
233   * <p>Note that if {@code list} is a {@code List<String>}, then {@code ImmutableList.copyOf(list)}
234   * returns an {@code ImmutableList<String>} containing each of the strings in {@code list}, while
235   * {@code ImmutableList.of(list)} returns an {@code ImmutableList<List<String>>} containing one
236   * element (the given list itself).
237   *
238   * <p>This method is safe to use even when {@code elements} is a synchronized or concurrent
239   * collection that is currently being modified by another thread.
240   *
241   * @throws NullPointerException if {@code elements} contains a null element
242   */
243  public static <E> ImmutableList<E> copyOf(Collection<? extends E> elements) {
244    if (elements instanceof ImmutableCollection) {
245      @SuppressWarnings("unchecked") // all supported methods are covariant
246      ImmutableList<E> list = ((ImmutableCollection<E>) elements).asList();
247      return list.isPartialView() ? ImmutableList.<E>asImmutableList(list.toArray()) : list;
248    }
249    return construct(elements.toArray());
250  }
251
252  /**
253   * Returns an immutable list containing the given elements, in order.
254   *
255   * @throws NullPointerException if {@code elements} contains a null element
256   */
257  public static <E> ImmutableList<E> copyOf(Iterator<? extends E> elements) {
258    // We special-case for 0 or 1 elements, but going further is madness.
259    if (!elements.hasNext()) {
260      return of();
261    }
262    E first = elements.next();
263    if (!elements.hasNext()) {
264      return of(first);
265    } else {
266      return new ImmutableList.Builder<E>().add(first).addAll(elements).build();
267    }
268  }
269
270  /**
271   * Returns an immutable list containing the given elements, in order.
272   *
273   * @throws NullPointerException if {@code elements} contains a null element
274   * @since 3.0
275   */
276  public static <E> ImmutableList<E> copyOf(E[] elements) {
277    return (elements.length == 0)
278        ? ImmutableList.<E>of()
279        : ImmutableList.<E>construct(elements.clone());
280  }
281
282  /**
283   * Returns an immutable list containing the given elements, sorted according to their natural
284   * order. The sorting algorithm used is stable, so elements that compare as equal will stay in the
285   * order in which they appear in the input.
286   *
287   * <p>If your data has no duplicates, or you wish to deduplicate elements, use {@code
288   * ImmutableSortedSet.copyOf(elements)}; if you want a {@code List} you can use its {@code
289   * asList()} view.
290   *
291   * <p><b>Java 8 users:</b> If you want to convert a {@link java.util.stream.Stream} to a sorted
292   * {@code ImmutableList}, use {@code stream.sorted().collect(toImmutableList())}.
293   *
294   * @throws NullPointerException if any element in the input is null
295   * @since 21.0
296   */
297  public static <E extends Comparable<? super E>> ImmutableList<E> sortedCopyOf(
298      Iterable<? extends E> elements) {
299    Comparable<?>[] array = Iterables.toArray(elements, new Comparable<?>[0]);
300    checkElementsNotNull((Object[]) array);
301    Arrays.sort(array);
302    return asImmutableList(array);
303  }
304
305  /**
306   * Returns an immutable list containing the given elements, in sorted order relative to the
307   * specified comparator. The sorting algorithm used is stable, so elements that compare as equal
308   * will stay in the order in which they appear in the input.
309   *
310   * <p>If your data has no duplicates, or you wish to deduplicate elements, use {@code
311   * ImmutableSortedSet.copyOf(comparator, elements)}; if you want a {@code List} you can use its
312   * {@code asList()} view.
313   *
314   * <p><b>Java 8 users:</b> If you want to convert a {@link java.util.stream.Stream} to a sorted
315   * {@code ImmutableList}, use {@code stream.sorted(comparator).collect(toImmutableList())}.
316   *
317   * @throws NullPointerException if any element in the input is null
318   * @since 21.0
319   */
320  public static <E> ImmutableList<E> sortedCopyOf(
321      Comparator<? super E> comparator, Iterable<? extends E> elements) {
322    checkNotNull(comparator);
323    @SuppressWarnings("unchecked") // all supported methods are covariant
324    E[] array = (E[]) Iterables.toArray(elements);
325    checkElementsNotNull(array);
326    Arrays.sort(array, comparator);
327    return asImmutableList(array);
328  }
329
330  /** Views the array as an immutable list. Checks for nulls; does not copy. */
331  private static <E> ImmutableList<E> construct(Object... elements) {
332    return asImmutableList(checkElementsNotNull(elements));
333  }
334
335  /**
336   * Views the array as an immutable list. Does not check for nulls; does not copy.
337   *
338   * <p>The array must be internally created.
339   */
340  static <E> ImmutableList<E> asImmutableList(Object[] elements) {
341    return asImmutableList(elements, elements.length);
342  }
343
344  /** Views the array as an immutable list. Does not check for nulls. */
345  static <E> ImmutableList<E> asImmutableList(@Nullable Object[] elements, int length) {
346    if (length == 0) {
347      return of();
348    }
349    return new RegularImmutableList<E>(elements, length);
350  }
351
352  ImmutableList() {}
353
354  // This declaration is needed to make List.iterator() and
355  // ImmutableCollection.iterator() consistent.
356  @Override
357  public UnmodifiableIterator<E> iterator() {
358    return listIterator();
359  }
360
361  @Override
362  public UnmodifiableListIterator<E> listIterator() {
363    return listIterator(0);
364  }
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  /** A singleton implementation of iterator() for the empty ImmutableList. */
378  private static final UnmodifiableListIterator<Object> EMPTY_ITR =
379      new Itr<Object>(RegularImmutableList.EMPTY, 0);
380
381  static class Itr<E> extends AbstractIndexedListIterator<E> {
382    private final ImmutableList<E> list;
383
384    Itr(ImmutableList<E> list, int index) {
385      super(list.size(), index);
386      this.list = list;
387    }
388
389    @Override
390    protected E get(int index) {
391      return list.get(index);
392    }
393  }
394
395  @Override
396  public int indexOf(@CheckForNull Object object) {
397    return (object == null) ? -1 : Lists.indexOfImpl(this, object);
398  }
399
400  @Override
401  public int lastIndexOf(@CheckForNull Object object) {
402    return (object == null) ? -1 : Lists.lastIndexOfImpl(this, object);
403  }
404
405  @Override
406  public boolean contains(@CheckForNull Object object) {
407    return indexOf(object) >= 0;
408  }
409
410  // constrain the return type to ImmutableList<E>
411
412  /**
413   * Returns an immutable list of the elements between the specified {@code fromIndex}, inclusive,
414   * and {@code toIndex}, exclusive. (If {@code fromIndex} and {@code toIndex} are equal, the empty
415   * immutable list is returned.)
416   */
417  @Override
418  public ImmutableList<E> subList(int fromIndex, int toIndex) {
419    checkPositionIndexes(fromIndex, toIndex, size());
420    int length = toIndex - fromIndex;
421    if (length == size()) {
422      return this;
423    } else if (length == 0) {
424      return of();
425    } else {
426      return subListUnchecked(fromIndex, toIndex);
427    }
428  }
429
430  /**
431   * Called by the default implementation of {@link #subList} when {@code toIndex - fromIndex > 1},
432   * after index validation has already been performed.
433   */
434  ImmutableList<E> subListUnchecked(int fromIndex, int toIndex) {
435    return new SubList(fromIndex, toIndex - fromIndex);
436  }
437
438  class SubList extends ImmutableList<E> {
439    final transient int offset;
440    final transient int length;
441
442    SubList(int offset, int length) {
443      this.offset = offset;
444      this.length = length;
445    }
446
447    @Override
448    public int size() {
449      return length;
450    }
451
452    @Override
453    @CheckForNull
454    @Nullable
455    Object[] internalArray() {
456      return ImmutableList.this.internalArray();
457    }
458
459    @Override
460    int internalArrayStart() {
461      return ImmutableList.this.internalArrayStart() + offset;
462    }
463
464    @Override
465    int internalArrayEnd() {
466      return ImmutableList.this.internalArrayStart() + offset + 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   * Returns this list instance.
544   *
545   * @since 2.0
546   * @deprecated There is no reason to use this; it always returns {@code this}.
547   */
548  @InlineMe(replacement = "this")
549  @Deprecated
550  @Override
551  public final ImmutableList<E> asList() {
552    return this;
553  }
554
555  @Override
556  int copyIntoArray(@Nullable Object[] dst, int offset) {
557    // this loop is faster for RandomAccess instances, which ImmutableLists are
558    int size = size();
559    for (int i = 0; i < size; i++) {
560      dst[offset + i] = get(i);
561    }
562    return offset + size;
563  }
564
565  /**
566   * Returns a view of this immutable list in reverse order. For example, {@code ImmutableList.of(1,
567   * 2, 3).reverse()} is equivalent to {@code ImmutableList.of(3, 2, 1)}.
568   *
569   * @return a view of this immutable list in reverse order
570   * @since 7.0
571   */
572  public ImmutableList<E> reverse() {
573    return (size() <= 1) ? this : new ReverseImmutableList<E>(this);
574  }
575
576  private static class ReverseImmutableList<E> extends ImmutableList<E> {
577    private final transient ImmutableList<E> forwardList;
578
579    ReverseImmutableList(ImmutableList<E> backingList) {
580      this.forwardList = backingList;
581    }
582
583    private int reverseIndex(int index) {
584      return (size() - 1) - index;
585    }
586
587    private int reversePosition(int index) {
588      return size() - index;
589    }
590
591    @Override
592    public ImmutableList<E> reverse() {
593      return forwardList;
594    }
595
596    @Override
597    public boolean contains(@CheckForNull Object object) {
598      return forwardList.contains(object);
599    }
600
601    @Override
602    public int indexOf(@CheckForNull Object object) {
603      int index = forwardList.lastIndexOf(object);
604      return (index >= 0) ? reverseIndex(index) : -1;
605    }
606
607    @Override
608    public int lastIndexOf(@CheckForNull Object object) {
609      int index = forwardList.indexOf(object);
610      return (index >= 0) ? reverseIndex(index) : -1;
611    }
612
613    @Override
614    public ImmutableList<E> subList(int fromIndex, int toIndex) {
615      checkPositionIndexes(fromIndex, toIndex, size());
616      return forwardList.subList(reversePosition(toIndex), reversePosition(fromIndex)).reverse();
617    }
618
619    @Override
620    public E get(int index) {
621      checkElementIndex(index, size());
622      return forwardList.get(reverseIndex(index));
623    }
624
625    @Override
626    public int size() {
627      return forwardList.size();
628    }
629
630    @Override
631    boolean isPartialView() {
632      return forwardList.isPartialView();
633    }
634  }
635
636  @Override
637  public boolean equals(@CheckForNull Object obj) {
638    return Lists.equalsImpl(this, obj);
639  }
640
641  @Override
642  public int hashCode() {
643    int hashCode = 1;
644    int n = size();
645    for (int i = 0; i < n; i++) {
646      hashCode = 31 * hashCode + get(i).hashCode();
647
648      hashCode = ~~hashCode;
649      // needed to deal with GWT integer overflow
650    }
651    return hashCode;
652  }
653
654  /*
655   * Serializes ImmutableLists as their logical contents. This ensures that
656   * implementation types do not leak into the serialized representation.
657   */
658  @J2ktIncompatible // serialization
659  static class SerializedForm implements Serializable {
660    final Object[] elements;
661
662    SerializedForm(Object[] elements) {
663      this.elements = elements;
664    }
665
666    Object readResolve() {
667      return copyOf(elements);
668    }
669
670    private static final long serialVersionUID = 0;
671  }
672
673  @J2ktIncompatible // serialization
674  private void readObject(ObjectInputStream stream) throws InvalidObjectException {
675    throw new InvalidObjectException("Use SerializedForm");
676  }
677
678  @Override
679  @J2ktIncompatible // serialization
680  Object writeReplace() {
681    return new SerializedForm(toArray());
682  }
683
684  /**
685   * Returns a new builder. The generated builder is equivalent to the builder created by the {@link
686   * Builder} constructor.
687   */
688  public static <E> Builder<E> builder() {
689    return new Builder<E>();
690  }
691
692  /**
693   * Returns a new builder, expecting the specified number of elements to be added.
694   *
695   * <p>If {@code expectedSize} is exactly the number of elements added to the builder before {@link
696   * Builder#build} is called, the builder is likely to perform better than an unsized {@link
697   * #builder()} would have.
698   *
699   * <p>It is not specified if any performance benefits apply if {@code expectedSize} is close to,
700   * but not exactly, the number of elements added to the builder.
701   *
702   * @since 23.1
703   */
704  public static <E> Builder<E> builderWithExpectedSize(int expectedSize) {
705    checkNonnegative(expectedSize, "expectedSize");
706    return new ImmutableList.Builder<E>(expectedSize);
707  }
708
709  /**
710   * A builder for creating immutable list instances, especially {@code public static final} lists
711   * ("constant lists"). Example:
712   *
713   * <pre>{@code
714   * public static final ImmutableList<Color> GOOGLE_COLORS
715   *     = new ImmutableList.Builder<Color>()
716   *         .addAll(WEBSAFE_COLORS)
717   *         .add(new Color(0, 191, 255))
718   *         .build();
719   * }</pre>
720   *
721   * <p>Elements appear in the resulting list in the same order they were added to the builder.
722   *
723   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
724   * multiple lists in series. Each new list contains all the elements of the ones created before
725   * it.
726   *
727   * @since 2.0
728   */
729  public static final class Builder<E> extends ImmutableCollection.ArrayBasedBuilder<E> {
730    /**
731     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
732     * ImmutableList#builder}.
733     */
734    public Builder() {
735      this(DEFAULT_INITIAL_CAPACITY);
736    }
737
738    Builder(int capacity) {
739      super(capacity);
740    }
741
742    /**
743     * Adds {@code element} to the {@code ImmutableList}.
744     *
745     * @param element the element to add
746     * @return this {@code Builder} object
747     * @throws NullPointerException if {@code element} is null
748     */
749    @CanIgnoreReturnValue
750    @Override
751    public Builder<E> add(E element) {
752      super.add(element);
753      return this;
754    }
755
756    /**
757     * Adds each element of {@code elements} to the {@code ImmutableList}.
758     *
759     * @param elements the {@code Iterable} to add to the {@code ImmutableList}
760     * @return this {@code Builder} object
761     * @throws NullPointerException if {@code elements} is null or contains a null element
762     */
763    @CanIgnoreReturnValue
764    @Override
765    public Builder<E> add(E... elements) {
766      super.add(elements);
767      return this;
768    }
769
770    /**
771     * Adds each element of {@code elements} to the {@code ImmutableList}.
772     *
773     * @param elements the {@code Iterable} to add to the {@code ImmutableList}
774     * @return this {@code Builder} object
775     * @throws NullPointerException if {@code elements} is null or contains a null element
776     */
777    @CanIgnoreReturnValue
778    @Override
779    public Builder<E> addAll(Iterable<? extends E> elements) {
780      super.addAll(elements);
781      return this;
782    }
783
784    /**
785     * Adds each element of {@code elements} to the {@code ImmutableList}.
786     *
787     * @param elements the {@code Iterator} to add to the {@code ImmutableList}
788     * @return this {@code Builder} object
789     * @throws NullPointerException if {@code elements} is null or contains a null element
790     */
791    @CanIgnoreReturnValue
792    @Override
793    public Builder<E> addAll(Iterator<? extends E> elements) {
794      super.addAll(elements);
795      return this;
796    }
797
798    @CanIgnoreReturnValue
799    Builder<E> combine(Builder<E> other) {
800      addAll(other.contents, other.size);
801      return this;
802    }
803
804    /**
805     * Returns a newly-created {@code ImmutableList} based on the contents of the {@code Builder}.
806     */
807    @Override
808    public ImmutableList<E> build() {
809      forceCopy = true;
810      return asImmutableList(contents, size);
811    }
812  }
813}