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() ? 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  @Deprecated
425  @Override
426  public final boolean addAll(int index, Collection<? extends E> newElements) {
427    throw new UnsupportedOperationException();
428  }
429
430  /**
431   * Guaranteed to throw an exception and leave the list unmodified.
432   *
433   * @throws UnsupportedOperationException always
434   * @deprecated Unsupported operation.
435   */
436  @Deprecated
437  @Override
438  public final E set(int index, E element) {
439    throw new UnsupportedOperationException();
440  }
441
442  /**
443   * Guaranteed to throw an exception and leave the list unmodified.
444   *
445   * @throws UnsupportedOperationException always
446   * @deprecated Unsupported operation.
447   */
448  @Deprecated
449  @Override
450  public final void add(int index, E element) {
451    throw new UnsupportedOperationException();
452  }
453
454  /**
455   * Guaranteed to throw an exception and leave the list unmodified.
456   *
457   * @throws UnsupportedOperationException always
458   * @deprecated Unsupported operation.
459   */
460  @Deprecated
461  @Override
462  public final E remove(int index) {
463    throw new UnsupportedOperationException();
464  }
465
466  /**
467   * Returns this list instance.
468   *
469   * @since 2.0
470   */
471  @Override
472  public final ImmutableList<E> asList() {
473    return this;
474  }
475
476  @Override
477  int copyIntoArray(Object[] dst, int offset) {
478    // this loop is faster for RandomAccess instances, which ImmutableLists are
479    int size = size();
480    for (int i = 0; i < size; i++) {
481      dst[offset + i] = get(i);
482    }
483    return offset + size;
484  }
485
486  /**
487   * Returns a view of this immutable list in reverse order. For example, {@code
488   * ImmutableList.of(1, 2, 3).reverse()} is equivalent to {@code
489   * ImmutableList.of(3, 2, 1)}.
490   *
491   * @return a view of this immutable list in reverse order
492   * @since 7.0
493   */
494  public ImmutableList<E> reverse() {
495    return (size() <= 1) ? this : new ReverseImmutableList<E>(this);
496  }
497
498  private static class ReverseImmutableList<E> extends ImmutableList<E> {
499    private final transient ImmutableList<E> forwardList;
500
501    ReverseImmutableList(ImmutableList<E> backingList) {
502      this.forwardList = backingList;
503    }
504
505    private int reverseIndex(int index) {
506      return (size() - 1) - index;
507    }
508
509    private int reversePosition(int index) {
510      return size() - index;
511    }
512
513    @Override
514    public ImmutableList<E> reverse() {
515      return forwardList;
516    }
517
518    @Override
519    public boolean contains(@Nullable Object object) {
520      return forwardList.contains(object);
521    }
522
523    @Override
524    public int indexOf(@Nullable Object object) {
525      int index = forwardList.lastIndexOf(object);
526      return (index >= 0) ? reverseIndex(index) : -1;
527    }
528
529    @Override
530    public int lastIndexOf(@Nullable Object object) {
531      int index = forwardList.indexOf(object);
532      return (index >= 0) ? reverseIndex(index) : -1;
533    }
534
535    @Override
536    public ImmutableList<E> subList(int fromIndex, int toIndex) {
537      checkPositionIndexes(fromIndex, toIndex, size());
538      return forwardList.subList(reversePosition(toIndex), reversePosition(fromIndex)).reverse();
539    }
540
541    @Override
542    public E get(int index) {
543      checkElementIndex(index, size());
544      return forwardList.get(reverseIndex(index));
545    }
546
547    @Override
548    public int size() {
549      return forwardList.size();
550    }
551
552    @Override
553    boolean isPartialView() {
554      return forwardList.isPartialView();
555    }
556  }
557
558  @Override
559  public boolean equals(@Nullable Object obj) {
560    return Lists.equalsImpl(this, obj);
561  }
562
563  @Override
564  public int hashCode() {
565    int hashCode = 1;
566    int n = size();
567    for (int i = 0; i < n; i++) {
568      hashCode = 31 * hashCode + get(i).hashCode();
569
570      hashCode = ~~hashCode;
571      // needed to deal with GWT integer overflow
572    }
573    return hashCode;
574  }
575
576  /*
577   * Serializes ImmutableLists as their logical contents. This ensures that
578   * implementation types do not leak into the serialized representation.
579   */
580  static class SerializedForm implements Serializable {
581    final Object[] elements;
582
583    SerializedForm(Object[] elements) {
584      this.elements = elements;
585    }
586
587    Object readResolve() {
588      return copyOf(elements);
589    }
590
591    private static final long serialVersionUID = 0;
592  }
593
594  private void readObject(ObjectInputStream stream) throws InvalidObjectException {
595    throw new InvalidObjectException("Use SerializedForm");
596  }
597
598  @Override
599  Object writeReplace() {
600    return new SerializedForm(toArray());
601  }
602
603  /**
604   * Returns a new builder. The generated builder is equivalent to the builder
605   * created by the {@link Builder} constructor.
606   */
607  public static <E> Builder<E> builder() {
608    return new Builder<E>();
609  }
610
611  /**
612   * A builder for creating immutable list instances, especially {@code public
613   * static final} lists ("constant lists"). Example: <pre>   {@code
614   *
615   *   public static final ImmutableList<Color> GOOGLE_COLORS
616   *       = new ImmutableList.Builder<Color>()
617   *           .addAll(WEBSAFE_COLORS)
618   *           .add(new Color(0, 191, 255))
619   *           .build();}</pre>
620   *
621   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple
622   * times to build multiple lists in series. Each new list contains all the
623   * elements of the ones created before it.
624   *
625   * @since 2.0
626   */
627  public static final class Builder<E> extends ImmutableCollection.ArrayBasedBuilder<E> {
628    /**
629     * Creates a new builder. The returned builder is equivalent to the builder
630     * generated by {@link ImmutableList#builder}.
631     */
632    public Builder() {
633      this(DEFAULT_INITIAL_CAPACITY);
634    }
635
636    // TODO(lowasser): consider exposing this
637    Builder(int capacity) {
638      super(capacity);
639    }
640
641    /**
642     * Adds {@code element} to the {@code ImmutableList}.
643     *
644     * @param element the element to add
645     * @return this {@code Builder} object
646     * @throws NullPointerException if {@code element} is null
647     */
648    @Override
649    public Builder<E> add(E element) {
650      super.add(element);
651      return this;
652    }
653
654    /**
655     * Adds each element of {@code elements} to the {@code ImmutableList}.
656     *
657     * @param elements the {@code Iterable} to add to the {@code ImmutableList}
658     * @return this {@code Builder} object
659     * @throws NullPointerException if {@code elements} is null or contains a
660     *     null element
661     */
662    @Override
663    public Builder<E> addAll(Iterable<? extends E> elements) {
664      super.addAll(elements);
665      return this;
666    }
667
668    /**
669     * Adds each element of {@code elements} to the {@code ImmutableList}.
670     *
671     * @param elements the {@code Iterable} to add to the {@code ImmutableList}
672     * @return this {@code Builder} object
673     * @throws NullPointerException if {@code elements} is null or contains a
674     *     null element
675     */
676    @Override
677    public Builder<E> add(E... elements) {
678      super.add(elements);
679      return this;
680    }
681
682    /**
683     * Adds each element of {@code elements} to the {@code ImmutableList}.
684     *
685     * @param elements the {@code Iterable} to add to the {@code ImmutableList}
686     * @return this {@code Builder} object
687     * @throws NullPointerException if {@code elements} is null or contains a
688     *     null element
689     */
690    @Override
691    public Builder<E> addAll(Iterator<? extends E> elements) {
692      super.addAll(elements);
693      return this;
694    }
695
696    /**
697     * Returns a newly-created {@code ImmutableList} based on the contents of
698     * the {@code Builder}.
699     */
700    @Override
701    public ImmutableList<E> build() {
702      return asImmutableList(contents, size);
703    }
704  }
705}