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