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