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.checkElementIndex;
020import static com.google.common.base.Preconditions.checkNotNull;
021import static com.google.common.base.Preconditions.checkPositionIndexes;
022import static com.google.common.collect.ObjectArrays.arraysCopyOf;
023import static com.google.common.collect.ObjectArrays.checkElementsNotNull;
024import static com.google.common.collect.RegularImmutableList.EMPTY;
025
026import com.google.common.annotations.GwtCompatible;
027import com.google.errorprone.annotations.CanIgnoreReturnValue;
028import java.io.InvalidObjectException;
029import java.io.ObjectInputStream;
030import java.io.Serializable;
031import java.util.Collection;
032import java.util.Collections;
033import java.util.Iterator;
034import java.util.List;
035import java.util.RandomAccess;
036import javax.annotation.Nullable;
037
038/**
039 * A {@link List} whose contents will never change, with many other important properties detailed at
040 * {@link ImmutableCollection}.
041 *
042 * <p>See the Guava User Guide article on <a href=
043 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">
044 * immutable collections</a>.
045 *
046 * @see ImmutableMap
047 * @see ImmutableSet
048 * @author Kevin Bourrillion
049 * @since 2.0
050 */
051@GwtCompatible(serializable = true, emulated = true)
052@SuppressWarnings("serial") // we're overriding default serialization
053public abstract class ImmutableList<E> extends ImmutableCollection<E>
054    implements List<E>, RandomAccess {
055  /**
056   * Returns the empty immutable list. This list behaves and performs comparably
057   * to {@link Collections#emptyList}, and is preferable mainly for consistency
058   * and maintainability of your code.
059   */
060  // Casting to any type is safe because the list will never hold any elements.
061  @SuppressWarnings("unchecked")
062  public static <E> ImmutableList<E> of() {
063    return (ImmutableList<E>) EMPTY;
064  }
065
066  /**
067   * Returns an immutable list containing a single element. This list behaves
068   * and performs comparably to {@link Collections#singleton}, but will not
069   * accept a null element. It is preferable mainly for consistency and
070   * maintainability of your code.
071   *
072   * @throws NullPointerException if {@code element} is null
073   */
074  public static <E> ImmutableList<E> of(E element) {
075    return new SingletonImmutableList<E>(element);
076  }
077
078  /**
079   * Returns an immutable list containing the given elements, in order.
080   *
081   * @throws NullPointerException if any element is null
082   */
083  public static <E> ImmutableList<E> of(E e1, E e2) {
084    return construct(e1, e2);
085  }
086
087  /**
088   * Returns an immutable list containing the given elements, in order.
089   *
090   * @throws NullPointerException if any element is null
091   */
092  public static <E> ImmutableList<E> of(E e1, E e2, E e3) {
093    return construct(e1, e2, e3);
094  }
095
096  /**
097   * Returns an immutable list containing the given elements, in order.
098   *
099   * @throws NullPointerException if any element is null
100   */
101  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4) {
102    return construct(e1, e2, e3, e4);
103  }
104
105  /**
106   * Returns an immutable list containing the given elements, in order.
107   *
108   * @throws NullPointerException if any element is null
109   */
110  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5) {
111    return construct(e1, e2, e3, e4, e5);
112  }
113
114  /**
115   * Returns an immutable list containing the given elements, in order.
116   *
117   * @throws NullPointerException if any element is null
118   */
119  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6) {
120    return construct(e1, e2, e3, e4, e5, e6);
121  }
122
123  /**
124   * Returns an immutable list containing the given elements, in order.
125   *
126   * @throws NullPointerException if any element is null
127   */
128  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7) {
129    return construct(e1, e2, e3, e4, e5, e6, e7);
130  }
131
132  /**
133   * Returns an immutable list containing the given elements, in order.
134   *
135   * @throws NullPointerException if any element is null
136   */
137  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) {
138    return construct(e1, e2, e3, e4, e5, e6, e7, e8);
139  }
140
141  /**
142   * Returns an immutable list containing the given elements, in order.
143   *
144   * @throws NullPointerException if any element is null
145   */
146  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) {
147    return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9);
148  }
149
150  /**
151   * Returns an immutable list containing the given elements, in order.
152   *
153   * @throws NullPointerException if any element is null
154   */
155  public static <E> ImmutableList<E> of(
156      E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) {
157    return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10);
158  }
159
160  /**
161   * Returns an immutable list containing the given elements, in order.
162   *
163   * @throws NullPointerException if any element is null
164   */
165  public static <E> ImmutableList<E> of(
166      E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11) {
167    return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11);
168  }
169
170  // These go up to eleven. After that, you just get the varargs form, and
171  // whatever warnings might come along with it. :(
172
173  /**
174   * Returns an immutable list containing the given elements, in order.
175   *
176   * @throws NullPointerException if any element is null
177   * @since 3.0 (source-compatible since 2.0)
178   */
179  @SafeVarargs // For Eclipse. For internal javac we have disabled this pointless type of warning.
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, E e11, E e12, E... others) {
182    Object[] array = new Object[12 + others.length];
183    array[0] = e1;
184    array[1] = e2;
185    array[2] = e3;
186    array[3] = e4;
187    array[4] = e5;
188    array[5] = e6;
189    array[6] = e7;
190    array[7] = e8;
191    array[8] = e9;
192    array[9] = e10;
193    array[10] = e11;
194    array[11] = e12;
195    System.arraycopy(others, 0, array, 12, others.length);
196    return construct(array);
197  }
198
199  /**
200   * Returns an immutable list containing the given elements, in order. If
201   * {@code elements} is a {@link Collection}, this method behaves exactly as
202   * {@link #copyOf(Collection)}; otherwise, it behaves exactly as {@code
203   * copyOf(elements.iterator()}.
204   *
205   * @throws NullPointerException if any of {@code elements} is null
206   */
207  public static <E> ImmutableList<E> copyOf(Iterable<? extends E> elements) {
208    checkNotNull(elements); // TODO(kevinb): is this here only for GWT?
209    return (elements instanceof Collection)
210        ? copyOf((Collection<? extends E>) elements)
211        : copyOf(elements.iterator());
212  }
213
214  /**
215   * Returns an immutable list containing the given elements, in order.
216   *
217   * <p>Despite the method name, this method attempts to avoid actually copying
218   * the data when it is safe to do so. The exact circumstances under which a
219   * copy will or will not be performed are undocumented and subject to change.
220   *
221   * <p>Note that if {@code list} is a {@code List<String>}, then {@code
222   * ImmutableList.copyOf(list)} returns an {@code ImmutableList<String>}
223   * containing each of the strings in {@code list}, while
224   * ImmutableList.of(list)} returns an {@code ImmutableList<List<String>>}
225   * containing one element (the given list itself).
226   *
227   * <p>This method is safe to use even when {@code elements} is a synchronized
228   * or concurrent collection that is currently being modified by another
229   * thread.
230   *
231   * @throws NullPointerException if any of {@code elements} is null
232   */
233  public static <E> ImmutableList<E> copyOf(Collection<? extends E> elements) {
234    if (elements instanceof ImmutableCollection) {
235      @SuppressWarnings("unchecked") // all supported methods are covariant
236      ImmutableList<E> list = ((ImmutableCollection<E>) elements).asList();
237      return list.isPartialView() ? ImmutableList.<E>asImmutableList(list.toArray()) : list;
238    }
239    return construct(elements.toArray());
240  }
241
242  /**
243   * Returns an immutable list containing the given elements, in order.
244   *
245   * @throws NullPointerException if any of {@code elements} is null
246   */
247  public static <E> ImmutableList<E> copyOf(Iterator<? extends E> elements) {
248    // We special-case for 0 or 1 elements, but going further is madness.
249    if (!elements.hasNext()) {
250      return of();
251    }
252    E first = elements.next();
253    if (!elements.hasNext()) {
254      return of(first);
255    } else {
256      return new ImmutableList.Builder<E>().add(first).addAll(elements).build();
257    }
258  }
259
260  /**
261   * Returns an immutable list containing the given elements, in order.
262   *
263   * @throws NullPointerException if any of {@code elements} is null
264   * @since 3.0
265   */
266  public static <E> ImmutableList<E> copyOf(E[] elements) {
267    switch (elements.length) {
268      case 0:
269        return ImmutableList.of();
270      case 1:
271        return new SingletonImmutableList<E>(elements[0]);
272      default:
273        return new RegularImmutableList<E>(checkElementsNotNull(elements.clone()));
274    }
275  }
276
277  /**
278   * Views the array as an immutable list.  Checks for nulls; does not copy.
279   */
280  private static <E> ImmutableList<E> construct(Object... elements) {
281    return asImmutableList(checkElementsNotNull(elements));
282  }
283
284  /**
285   * Views the array as an immutable list.  Does not check for nulls; does not copy.
286   *
287   * <p>The array must be internally created.
288   */
289  static <E> ImmutableList<E> asImmutableList(Object[] elements) {
290    return asImmutableList(elements, elements.length);
291  }
292
293  /**
294   * Views the array as an immutable list. Copies if the specified range does not cover the complete
295   * array. Does not check for nulls.
296   */
297  static <E> ImmutableList<E> asImmutableList(Object[] elements, int length) {
298    switch (length) {
299      case 0:
300        return of();
301      case 1:
302        @SuppressWarnings("unchecked") // collection had only Es in it
303        ImmutableList<E> list = new SingletonImmutableList<E>((E) elements[0]);
304        return list;
305      default:
306        if (length < elements.length) {
307          elements = arraysCopyOf(elements, length);
308        }
309        return new RegularImmutableList<E>(elements);
310    }
311  }
312
313  ImmutableList() {}
314
315  // This declaration is needed to make List.iterator() and
316  // ImmutableCollection.iterator() consistent.
317  @Override
318  public UnmodifiableIterator<E> iterator() {
319    return listIterator();
320  }
321
322  @Override
323  public UnmodifiableListIterator<E> listIterator() {
324    return listIterator(0);
325  }
326
327  @Override
328  public UnmodifiableListIterator<E> listIterator(int index) {
329    return new AbstractIndexedListIterator<E>(size(), index) {
330      @Override
331      protected E get(int index) {
332        return ImmutableList.this.get(index);
333      }
334    };
335  }
336
337  @Override
338  public int indexOf(@Nullable Object object) {
339    return (object == null) ? -1 : Lists.indexOfImpl(this, object);
340  }
341
342  @Override
343  public int lastIndexOf(@Nullable Object object) {
344    return (object == null) ? -1 : Lists.lastIndexOfImpl(this, object);
345  }
346
347  @Override
348  public boolean contains(@Nullable Object object) {
349    return indexOf(object) >= 0;
350  }
351
352  // constrain the return type to ImmutableList<E>
353
354  /**
355   * Returns an immutable list of the elements between the specified {@code
356   * fromIndex}, inclusive, and {@code toIndex}, exclusive. (If {@code
357   * fromIndex} and {@code toIndex} are equal, the empty immutable list is
358   * returned.)
359   */
360  @Override
361  public ImmutableList<E> subList(int fromIndex, int toIndex) {
362    checkPositionIndexes(fromIndex, toIndex, size());
363    int length = toIndex - fromIndex;
364    if (length == size()) {
365      return this;
366    }
367    switch (length) {
368      case 0:
369        return of();
370      case 1:
371        return of(get(fromIndex));
372      default:
373        return subListUnchecked(fromIndex, toIndex);
374    }
375  }
376
377  /**
378   * Called by the default implementation of {@link #subList} when {@code
379   * toIndex - fromIndex > 1}, after index validation has already been
380   * performed.
381   */
382  ImmutableList<E> subListUnchecked(int fromIndex, int toIndex) {
383    return new SubList(fromIndex, toIndex - fromIndex);
384  }
385
386  class SubList extends ImmutableList<E> {
387    final transient int offset;
388    final transient int length;
389
390    SubList(int offset, int length) {
391      this.offset = offset;
392      this.length = length;
393    }
394
395    @Override
396    public int size() {
397      return length;
398    }
399
400    @Override
401    public E get(int index) {
402      checkElementIndex(index, length);
403      return ImmutableList.this.get(index + offset);
404    }
405
406    @Override
407    public ImmutableList<E> subList(int fromIndex, int toIndex) {
408      checkPositionIndexes(fromIndex, toIndex, length);
409      return ImmutableList.this.subList(fromIndex + offset, toIndex + offset);
410    }
411
412    @Override
413    boolean isPartialView() {
414      return true;
415    }
416  }
417
418  /**
419   * Guaranteed to throw an exception and leave the list unmodified.
420   *
421   * @throws UnsupportedOperationException always
422   * @deprecated Unsupported operation.
423   */
424  @CanIgnoreReturnValue
425  @Deprecated
426  @Override
427  public final boolean addAll(int index, Collection<? extends E> newElements) {
428    throw new UnsupportedOperationException();
429  }
430
431  /**
432   * Guaranteed to throw an exception and leave the list unmodified.
433   *
434   * @throws UnsupportedOperationException always
435   * @deprecated Unsupported operation.
436   */
437  @CanIgnoreReturnValue
438  @Deprecated
439  @Override
440  public final E set(int index, E element) {
441    throw new UnsupportedOperationException();
442  }
443
444  /**
445   * Guaranteed to throw an exception and leave the list unmodified.
446   *
447   * @throws UnsupportedOperationException always
448   * @deprecated Unsupported operation.
449   */
450  @Deprecated
451  @Override
452  public final void add(int index, E element) {
453    throw new UnsupportedOperationException();
454  }
455
456  /**
457   * Guaranteed to throw an exception and leave the list unmodified.
458   *
459   * @throws UnsupportedOperationException always
460   * @deprecated Unsupported operation.
461   */
462  @CanIgnoreReturnValue
463  @Deprecated
464  @Override
465  public final E remove(int index) {
466    throw new UnsupportedOperationException();
467  }
468
469  /**
470   * Returns this list instance.
471   *
472   * @since 2.0
473   */
474  @Override
475  public final ImmutableList<E> asList() {
476    return this;
477  }
478
479  @Override
480  int copyIntoArray(Object[] dst, int offset) {
481    // this loop is faster for RandomAccess instances, which ImmutableLists are
482    int size = size();
483    for (int i = 0; i < size; i++) {
484      dst[offset + i] = get(i);
485    }
486    return offset + size;
487  }
488
489  /**
490   * Returns a view of this immutable list in reverse order. For example, {@code
491   * ImmutableList.of(1, 2, 3).reverse()} is equivalent to {@code
492   * ImmutableList.of(3, 2, 1)}.
493   *
494   * @return a view of this immutable list in reverse order
495   * @since 7.0
496   */
497  public ImmutableList<E> reverse() {
498    return (size() <= 1) ? this : new ReverseImmutableList<E>(this);
499  }
500
501  private static class ReverseImmutableList<E> extends ImmutableList<E> {
502    private final transient ImmutableList<E> forwardList;
503
504    ReverseImmutableList(ImmutableList<E> backingList) {
505      this.forwardList = backingList;
506    }
507
508    private int reverseIndex(int index) {
509      return (size() - 1) - index;
510    }
511
512    private int reversePosition(int index) {
513      return size() - index;
514    }
515
516    @Override
517    public ImmutableList<E> reverse() {
518      return forwardList;
519    }
520
521    @Override
522    public boolean contains(@Nullable Object object) {
523      return forwardList.contains(object);
524    }
525
526    @Override
527    public int indexOf(@Nullable Object object) {
528      int index = forwardList.lastIndexOf(object);
529      return (index >= 0) ? reverseIndex(index) : -1;
530    }
531
532    @Override
533    public int lastIndexOf(@Nullable Object object) {
534      int index = forwardList.indexOf(object);
535      return (index >= 0) ? reverseIndex(index) : -1;
536    }
537
538    @Override
539    public ImmutableList<E> subList(int fromIndex, int toIndex) {
540      checkPositionIndexes(fromIndex, toIndex, size());
541      return forwardList.subList(reversePosition(toIndex), reversePosition(fromIndex)).reverse();
542    }
543
544    @Override
545    public E get(int index) {
546      checkElementIndex(index, size());
547      return forwardList.get(reverseIndex(index));
548    }
549
550    @Override
551    public int size() {
552      return forwardList.size();
553    }
554
555    @Override
556    boolean isPartialView() {
557      return forwardList.isPartialView();
558    }
559  }
560
561  @Override
562  public boolean equals(@Nullable Object obj) {
563    return Lists.equalsImpl(this, obj);
564  }
565
566  @Override
567  public int hashCode() {
568    int hashCode = 1;
569    int n = size();
570    for (int i = 0; i < n; i++) {
571      hashCode = 31 * hashCode + get(i).hashCode();
572
573      hashCode = ~~hashCode;
574      // needed to deal with GWT integer overflow
575    }
576    return hashCode;
577  }
578
579  /*
580   * Serializes ImmutableLists as their logical contents. This ensures that
581   * implementation types do not leak into the serialized representation.
582   */
583  static class SerializedForm implements Serializable {
584    final Object[] elements;
585
586    SerializedForm(Object[] elements) {
587      this.elements = elements;
588    }
589
590    Object readResolve() {
591      return copyOf(elements);
592    }
593
594    private static final long serialVersionUID = 0;
595  }
596
597  private void readObject(ObjectInputStream stream) throws InvalidObjectException {
598    throw new InvalidObjectException("Use SerializedForm");
599  }
600
601  @Override
602  Object writeReplace() {
603    return new SerializedForm(toArray());
604  }
605
606  /**
607   * Returns a new builder. The generated builder is equivalent to the builder
608   * created by the {@link Builder} constructor.
609   */
610  public static <E> Builder<E> builder() {
611    return new Builder<E>();
612  }
613
614  /**
615   * A builder for creating immutable list instances, especially {@code public
616   * static final} lists ("constant lists"). Example: <pre>   {@code
617   *
618   *   public static final ImmutableList<Color> GOOGLE_COLORS
619   *       = new ImmutableList.Builder<Color>()
620   *           .addAll(WEBSAFE_COLORS)
621   *           .add(new Color(0, 191, 255))
622   *           .build();}</pre>
623   *
624   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple
625   * times to build multiple lists in series. Each new list contains all the
626   * elements of the ones created before it.
627   *
628   * @since 2.0
629   */
630  public static final class Builder<E> extends ImmutableCollection.ArrayBasedBuilder<E> {
631    /**
632     * Creates a new builder. The returned builder is equivalent to the builder
633     * generated by {@link ImmutableList#builder}.
634     */
635    public Builder() {
636      this(DEFAULT_INITIAL_CAPACITY);
637    }
638
639    // TODO(lowasser): consider exposing this
640    Builder(int capacity) {
641      super(capacity);
642    }
643
644    /**
645     * Adds {@code element} to the {@code ImmutableList}.
646     *
647     * @param element the element to add
648     * @return this {@code Builder} object
649     * @throws NullPointerException if {@code element} is null
650     */
651    @CanIgnoreReturnValue
652    @Override
653    public Builder<E> add(E element) {
654      super.add(element);
655      return this;
656    }
657
658    /**
659     * Adds each element of {@code elements} to the {@code ImmutableList}.
660     *
661     * @param elements the {@code Iterable} to add to the {@code ImmutableList}
662     * @return this {@code Builder} object
663     * @throws NullPointerException if {@code elements} is null or contains a
664     *     null element
665     */
666    @CanIgnoreReturnValue
667    @Override
668    public Builder<E> addAll(Iterable<? extends E> elements) {
669      super.addAll(elements);
670      return this;
671    }
672
673    /**
674     * Adds each element of {@code elements} to the {@code ImmutableList}.
675     *
676     * @param elements the {@code Iterable} to add to the {@code ImmutableList}
677     * @return this {@code Builder} object
678     * @throws NullPointerException if {@code elements} is null or contains a
679     *     null element
680     */
681    @CanIgnoreReturnValue
682    @Override
683    public Builder<E> add(E... elements) {
684      super.add(elements);
685      return this;
686    }
687
688    /**
689     * Adds each element of {@code elements} to the {@code ImmutableList}.
690     *
691     * @param elements the {@code Iterable} to add to the {@code ImmutableList}
692     * @return this {@code Builder} object
693     * @throws NullPointerException if {@code elements} is null or contains a
694     *     null element
695     */
696    @CanIgnoreReturnValue
697    @Override
698    public Builder<E> addAll(Iterator<? extends E> elements) {
699      super.addAll(elements);
700      return this;
701    }
702
703    /**
704     * Returns a newly-created {@code ImmutableList} based on the contents of
705     * the {@code Builder}.
706     */
707    @Override
708    public ImmutableList<E> build() {
709      return asImmutableList(contents, size);
710    }
711  }
712}