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