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