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