001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.base.Preconditions.checkElementIndex;
021import static com.google.common.base.Preconditions.checkNotNull;
022import static com.google.common.base.Preconditions.checkPositionIndex;
023import static com.google.common.base.Preconditions.checkPositionIndexes;
024import static com.google.common.base.Preconditions.checkState;
025import static com.google.common.collect.CollectPreconditions.checkRemove;
026
027import com.google.common.annotations.Beta;
028import com.google.common.annotations.GwtCompatible;
029import com.google.common.annotations.GwtIncompatible;
030import com.google.common.annotations.VisibleForTesting;
031import com.google.common.base.Function;
032import com.google.common.base.Objects;
033import com.google.common.math.IntMath;
034import com.google.common.primitives.Ints;
035
036import java.io.Serializable;
037import java.math.RoundingMode;
038import java.util.AbstractList;
039import java.util.AbstractSequentialList;
040import java.util.ArrayList;
041import java.util.Arrays;
042import java.util.Collection;
043import java.util.Collections;
044import java.util.Iterator;
045import java.util.LinkedList;
046import java.util.List;
047import java.util.ListIterator;
048import java.util.NoSuchElementException;
049import java.util.RandomAccess;
050import java.util.concurrent.CopyOnWriteArrayList;
051
052import javax.annotation.Nullable;
053
054/**
055 * Static utility methods pertaining to {@link List} instances. Also see this
056 * class's counterparts {@link Sets}, {@link Maps} and {@link Queues}.
057 *
058 * <p>See the Guava User Guide article on <a href=
059 * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Lists">
060 * {@code Lists}</a>.
061 *
062 * @author Kevin Bourrillion
063 * @author Mike Bostock
064 * @author Louis Wasserman
065 * @since 2.0 (imported from Google Collections Library)
066 */
067@GwtCompatible(emulated = true)
068public final class Lists {
069  private Lists() {}
070
071  // ArrayList
072
073  /**
074   * Creates a <i>mutable</i>, empty {@code ArrayList} instance.
075   *
076   * <p><b>Note:</b> if mutability is not required, use {@link
077   * ImmutableList#of()} instead.
078   *
079   * @return a new, empty {@code ArrayList}
080   */
081  @GwtCompatible(serializable = true)
082  public static <E> ArrayList<E> newArrayList() {
083    return new ArrayList<E>();
084  }
085
086  /**
087   * Creates a <i>mutable</i> {@code ArrayList} instance containing the given
088   * elements.
089   *
090   * <p><b>Note:</b> if mutability is not required and the elements are
091   * non-null, use an overload of {@link ImmutableList#of()} (for varargs) or
092   * {@link ImmutableList#copyOf(Object[])} (for an array) instead.
093   *
094   * @param elements the elements that the list should contain, in order
095   * @return a new {@code ArrayList} containing those elements
096   */
097  @GwtCompatible(serializable = true)
098  public static <E> ArrayList<E> newArrayList(E... elements) {
099    checkNotNull(elements); // for GWT
100    // Avoid integer overflow when a large array is passed in
101    int capacity = computeArrayListCapacity(elements.length);
102    ArrayList<E> list = new ArrayList<E>(capacity);
103    Collections.addAll(list, elements);
104    return list;
105  }
106
107  @VisibleForTesting static int computeArrayListCapacity(int arraySize) {
108    checkArgument(arraySize >= 0);
109
110    // TODO(kevinb): Figure out the right behavior, and document it
111    return Ints.saturatedCast(5L + arraySize + (arraySize / 10));
112  }
113
114  /**
115   * Creates a <i>mutable</i> {@code ArrayList} instance containing the given
116   * elements.
117   *
118   * <p><b>Note:</b> if mutability is not required and the elements are
119   * non-null, use {@link ImmutableList#copyOf(Iterator)} instead.
120   *
121   * @param elements the elements that the list should contain, in order
122   * @return a new {@code ArrayList} containing those elements
123   */
124  @GwtCompatible(serializable = true)
125  public static <E> ArrayList<E> newArrayList(Iterable<? extends E> elements) {
126    checkNotNull(elements); // for GWT
127    // Let ArrayList's sizing logic work, if possible
128    return (elements instanceof Collection)
129        ? new ArrayList<E>(Collections2.cast(elements))
130        : newArrayList(elements.iterator());
131  }
132
133  /**
134   * Creates a <i>mutable</i> {@code ArrayList} instance containing the given
135   * elements.
136   *
137   * <p><b>Note:</b> if mutability is not required and the elements are
138   * non-null, use {@link ImmutableList#copyOf(Iterator)} instead.
139   *
140   * @param elements the elements that the list should contain, in order
141   * @return a new {@code ArrayList} containing those elements
142   */
143  @GwtCompatible(serializable = true)
144  public static <E> ArrayList<E> newArrayList(Iterator<? extends E> elements) {
145    ArrayList<E> list = newArrayList();
146    Iterators.addAll(list, elements);
147    return list;
148  }
149
150  /**
151   * Creates an {@code ArrayList} instance backed by an array of the
152   * <i>exact</i> size specified; equivalent to
153   * {@link ArrayList#ArrayList(int)}.
154   *
155   * <p><b>Note:</b> if you know the exact size your list will be, consider
156   * using a fixed-size list ({@link Arrays#asList(Object[])}) or an {@link
157   * ImmutableList} instead of a growable {@link ArrayList}.
158   *
159   * <p><b>Note:</b> If you have only an <i>estimate</i> of the eventual size of
160   * the list, consider padding this estimate by a suitable amount, or simply
161   * use {@link #newArrayListWithExpectedSize(int)} instead.
162   *
163   * @param initialArraySize the exact size of the initial backing array for
164   *     the returned array list ({@code ArrayList} documentation calls this
165   *     value the "capacity")
166   * @return a new, empty {@code ArrayList} which is guaranteed not to resize
167   *     itself unless its size reaches {@code initialArraySize + 1}
168   * @throws IllegalArgumentException if {@code initialArraySize} is negative
169   */
170  @GwtCompatible(serializable = true)
171  public static <E> ArrayList<E> newArrayListWithCapacity(
172      int initialArraySize) {
173    checkArgument(initialArraySize >= 0);  // for GWT.
174    return new ArrayList<E>(initialArraySize);
175  }
176
177  /**
178   * Creates an {@code ArrayList} instance sized appropriately to hold an
179   * <i>estimated</i> number of elements without resizing. A small amount of
180   * padding is added in case the estimate is low.
181   *
182   * <p><b>Note:</b> If you know the <i>exact</i> number of elements the list
183   * will hold, or prefer to calculate your own amount of padding, refer to
184   * {@link #newArrayListWithCapacity(int)}.
185   *
186   * @param estimatedSize an estimate of the eventual {@link List#size()} of
187   *     the new list
188   * @return a new, empty {@code ArrayList}, sized appropriately to hold the
189   *     estimated number of elements
190   * @throws IllegalArgumentException if {@code estimatedSize} is negative
191   */
192  @GwtCompatible(serializable = true)
193  public static <E> ArrayList<E> newArrayListWithExpectedSize(
194      int estimatedSize) {
195    return new ArrayList<E>(computeArrayListCapacity(estimatedSize));
196  }
197
198  // LinkedList
199
200  /**
201   * Creates an empty {@code LinkedList} instance.
202   *
203   * <p><b>Note:</b> if you need an immutable empty {@link List}, use
204   * {@link ImmutableList#of()} instead.
205   *
206   * @return a new, empty {@code LinkedList}
207   */
208  @GwtCompatible(serializable = true)
209  public static <E> LinkedList<E> newLinkedList() {
210    return new LinkedList<E>();
211  }
212
213  /**
214   * Creates a {@code LinkedList} instance containing the given elements.
215   *
216   * @param elements the elements that the list should contain, in order
217   * @return a new {@code LinkedList} containing those elements
218   */
219  @GwtCompatible(serializable = true)
220  public static <E> LinkedList<E> newLinkedList(
221      Iterable<? extends E> elements) {
222    LinkedList<E> list = newLinkedList();
223    Iterables.addAll(list, elements);
224    return list;
225  }
226
227  /**
228   * Creates an empty {@code CopyOnWriteArrayList} instance.
229   *
230   * <p><b>Note:</b> if you need an immutable empty {@link List}, use
231   * {@link Collections#emptyList} instead.
232   *
233   * @return a new, empty {@code CopyOnWriteArrayList}
234   * @since 12.0
235   */
236  @GwtIncompatible("CopyOnWriteArrayList")
237  public static <E> CopyOnWriteArrayList<E> newCopyOnWriteArrayList() {
238    return new CopyOnWriteArrayList<E>();
239  }
240
241  /**
242   * Creates a {@code CopyOnWriteArrayList} instance containing the given elements.
243   *
244   * @param elements the elements that the list should contain, in order
245   * @return a new {@code CopyOnWriteArrayList} containing those elements
246   * @since 12.0
247   */
248  @GwtIncompatible("CopyOnWriteArrayList")
249  public static <E> CopyOnWriteArrayList<E> newCopyOnWriteArrayList(
250      Iterable<? extends E> elements) {
251    // We copy elements to an ArrayList first, rather than incurring the
252    // quadratic cost of adding them to the COWAL directly.
253    Collection<? extends E> elementsCollection = (elements instanceof Collection)
254        ? Collections2.cast(elements)
255        : newArrayList(elements);
256    return new CopyOnWriteArrayList<E>(elementsCollection);
257  }
258
259  /**
260   * Returns an unmodifiable list containing the specified first element and
261   * backed by the specified array of additional elements. Changes to the {@code
262   * rest} array will be reflected in the returned list. Unlike {@link
263   * Arrays#asList}, the returned list is unmodifiable.
264   *
265   * <p>This is useful when a varargs method needs to use a signature such as
266   * {@code (Foo firstFoo, Foo... moreFoos)}, in order to avoid overload
267   * ambiguity or to enforce a minimum argument count.
268   *
269   * <p>The returned list is serializable and implements {@link RandomAccess}.
270   *
271   * @param first the first element
272   * @param rest an array of additional elements, possibly empty
273   * @return an unmodifiable list containing the specified elements
274   */
275  public static <E> List<E> asList(@Nullable E first, E[] rest) {
276    return new OnePlusArrayList<E>(first, rest);
277  }
278
279  /** @see Lists#asList(Object, Object[]) */
280  private static class OnePlusArrayList<E> extends AbstractList<E>
281      implements Serializable, RandomAccess {
282    final E first;
283    final E[] rest;
284
285    OnePlusArrayList(@Nullable E first, E[] rest) {
286      this.first = first;
287      this.rest = checkNotNull(rest);
288    }
289    @Override public int size() {
290      return rest.length + 1;
291    }
292    @Override public E get(int index) {
293      // check explicitly so the IOOBE will have the right message
294      checkElementIndex(index, size());
295      return (index == 0) ? first : rest[index - 1];
296    }
297    private static final long serialVersionUID = 0;
298  }
299
300  /**
301   * Returns an unmodifiable list containing the specified first and second
302   * element, and backed by the specified array of additional elements. Changes
303   * to the {@code rest} array will be reflected in the returned list. Unlike
304   * {@link Arrays#asList}, the returned list is unmodifiable.
305   *
306   * <p>This is useful when a varargs method needs to use a signature such as
307   * {@code (Foo firstFoo, Foo secondFoo, Foo... moreFoos)}, in order to avoid
308   * overload ambiguity or to enforce a minimum argument count.
309   *
310   * <p>The returned list is serializable and implements {@link RandomAccess}.
311   *
312   * @param first the first element
313   * @param second the second element
314   * @param rest an array of additional elements, possibly empty
315   * @return an unmodifiable list containing the specified elements
316   */
317  public static <E> List<E> asList(
318      @Nullable E first, @Nullable E second, E[] rest) {
319    return new TwoPlusArrayList<E>(first, second, rest);
320  }
321
322  /** @see Lists#asList(Object, Object, Object[]) */
323  private static class TwoPlusArrayList<E> extends AbstractList<E>
324      implements Serializable, RandomAccess {
325    final E first;
326    final E second;
327    final E[] rest;
328
329    TwoPlusArrayList(@Nullable E first, @Nullable E second, E[] rest) {
330      this.first = first;
331      this.second = second;
332      this.rest = checkNotNull(rest);
333    }
334    @Override public int size() {
335      return rest.length + 2;
336    }
337    @Override public E get(int index) {
338      switch (index) {
339        case 0:
340          return first;
341        case 1:
342          return second;
343        default:
344          // check explicitly so the IOOBE will have the right message
345          checkElementIndex(index, size());
346          return rest[index - 2];
347      }
348    }
349    private static final long serialVersionUID = 0;
350  }
351
352  /**
353   * Returns every possible list that can be formed by choosing one element
354   * from each of the given lists in order; the "n-ary
355   * <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
356   * product</a>" of the lists. For example: <pre>   {@code
357   *
358   *   Lists.cartesianProduct(ImmutableList.of(
359   *       ImmutableList.of(1, 2),
360   *       ImmutableList.of("A", "B", "C")))}</pre>
361   *
362   * <p>returns a list containing six lists in the following order:
363   *
364   * <ul>
365   * <li>{@code ImmutableList.of(1, "A")}
366   * <li>{@code ImmutableList.of(1, "B")}
367   * <li>{@code ImmutableList.of(1, "C")}
368   * <li>{@code ImmutableList.of(2, "A")}
369   * <li>{@code ImmutableList.of(2, "B")}
370   * <li>{@code ImmutableList.of(2, "C")}
371   * </ul>
372   *
373   * <p>The result is guaranteed to be in the "traditional", lexicographical
374   * order for Cartesian products that you would get from nesting for loops:
375   * <pre>   {@code
376   *
377   *   for (B b0 : lists.get(0)) {
378   *     for (B b1 : lists.get(1)) {
379   *       ...
380   *       ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
381   *       // operate on tuple
382   *     }
383   *   }}</pre>
384   *
385   * <p>Note that if any input list is empty, the Cartesian product will also be
386   * empty. If no lists at all are provided (an empty list), the resulting
387   * Cartesian product has one element, an empty list (counter-intuitive, but
388   * mathematically consistent).
389   *
390   * <p><i>Performance notes:</i> while the cartesian product of lists of size
391   * {@code m, n, p} is a list of size {@code m x n x p}, its actual memory
392   * consumption is much smaller. When the cartesian product is constructed, the
393   * input lists are merely copied. Only as the resulting list is iterated are
394   * the individual lists created, and these are not retained after iteration.
395   *
396   * @param lists the lists to choose elements from, in the order that
397   *     the elements chosen from those lists should appear in the resulting
398   *     lists
399   * @param <B> any common base class shared by all axes (often just {@link
400   *     Object})
401   * @return the Cartesian product, as an immutable list containing immutable
402   *     lists
403   * @throws IllegalArgumentException if the size of the cartesian product would
404   *     be greater than {@link Integer#MAX_VALUE}
405   * @throws NullPointerException if {@code lists}, any one of the {@code lists},
406   *     or any element of a provided list is null
407   */ static <B> List<List<B>>
408      cartesianProduct(List<? extends List<? extends B>> lists) {
409    return CartesianList.create(lists);
410  }
411
412  /**
413   * Returns every possible list that can be formed by choosing one element
414   * from each of the given lists in order; the "n-ary
415   * <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
416   * product</a>" of the lists. For example: <pre>   {@code
417   *
418   *   Lists.cartesianProduct(ImmutableList.of(
419   *       ImmutableList.of(1, 2),
420   *       ImmutableList.of("A", "B", "C")))}</pre>
421   *
422   * <p>returns a list containing six lists in the following order:
423   *
424   * <ul>
425   * <li>{@code ImmutableList.of(1, "A")}
426   * <li>{@code ImmutableList.of(1, "B")}
427   * <li>{@code ImmutableList.of(1, "C")}
428   * <li>{@code ImmutableList.of(2, "A")}
429   * <li>{@code ImmutableList.of(2, "B")}
430   * <li>{@code ImmutableList.of(2, "C")}
431   * </ul>
432   *
433   * <p>The result is guaranteed to be in the "traditional", lexicographical
434   * order for Cartesian products that you would get from nesting for loops:
435   * <pre>   {@code
436   *
437   *   for (B b0 : lists.get(0)) {
438   *     for (B b1 : lists.get(1)) {
439   *       ...
440   *       ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
441   *       // operate on tuple
442   *     }
443   *   }}</pre>
444   *
445   * <p>Note that if any input list is empty, the Cartesian product will also be
446   * empty. If no lists at all are provided (an empty list), the resulting
447   * Cartesian product has one element, an empty list (counter-intuitive, but
448   * mathematically consistent).
449   *
450   * <p><i>Performance notes:</i> while the cartesian product of lists of size
451   * {@code m, n, p} is a list of size {@code m x n x p}, its actual memory
452   * consumption is much smaller. When the cartesian product is constructed, the
453   * input lists are merely copied. Only as the resulting list is iterated are
454   * the individual lists created, and these are not retained after iteration.
455   *
456   * @param lists the lists to choose elements from, in the order that
457   *     the elements chosen from those lists should appear in the resulting
458   *     lists
459   * @param <B> any common base class shared by all axes (often just {@link
460   *     Object})
461   * @return the Cartesian product, as an immutable list containing immutable
462   *     lists
463   * @throws IllegalArgumentException if the size of the cartesian product would
464   *     be greater than {@link Integer#MAX_VALUE}
465   * @throws NullPointerException if {@code lists}, any one of the
466   *     {@code lists}, or any element of a provided list is null
467   */ static <B> List<List<B>>
468      cartesianProduct(List<? extends B>... lists) {
469    return cartesianProduct(Arrays.asList(lists));
470  }
471
472  /**
473   * Returns a list that applies {@code function} to each element of {@code
474   * fromList}. The returned list is a transformed view of {@code fromList};
475   * changes to {@code fromList} will be reflected in the returned list and vice
476   * versa.
477   *
478   * <p>Since functions are not reversible, the transform is one-way and new
479   * items cannot be stored in the returned list. The {@code add},
480   * {@code addAll} and {@code set} methods are unsupported in the returned
481   * list.
482   *
483   * <p>The function is applied lazily, invoked when needed. This is necessary
484   * for the returned list to be a view, but it means that the function will be
485   * applied many times for bulk operations like {@link List#contains} and
486   * {@link List#hashCode}. For this to perform well, {@code function} should be
487   * fast. To avoid lazy evaluation when the returned list doesn't need to be a
488   * view, copy the returned list into a new list of your choosing.
489   *
490   * <p>If {@code fromList} implements {@link RandomAccess}, so will the
491   * returned list. The returned list is threadsafe if the supplied list and
492   * function are.
493   *
494   * <p>If only a {@code Collection} or {@code Iterable} input is available, use
495   * {@link Collections2#transform} or {@link Iterables#transform}.
496   *
497   * <p><b>Note:</b> serializing the returned list is implemented by serializing
498   * {@code fromList}, its contents, and {@code function} -- <i>not</i> by
499   * serializing the transformed values. This can lead to surprising behavior,
500   * so serializing the returned list is <b>not recommended</b>. Instead,
501   * copy the list using {@link ImmutableList#copyOf(Collection)} (for example),
502   * then serialize the copy. Other methods similar to this do not implement
503   * serialization at all for this reason.
504   */
505  public static <F, T> List<T> transform(
506      List<F> fromList, Function<? super F, ? extends T> function) {
507    return (fromList instanceof RandomAccess)
508        ? new TransformingRandomAccessList<F, T>(fromList, function)
509        : new TransformingSequentialList<F, T>(fromList, function);
510  }
511
512  /**
513   * Implementation of a sequential transforming list.
514   *
515   * @see Lists#transform
516   */
517  private static class TransformingSequentialList<F, T>
518      extends AbstractSequentialList<T> implements Serializable {
519    final List<F> fromList;
520    final Function<? super F, ? extends T> function;
521
522    TransformingSequentialList(
523        List<F> fromList, Function<? super F, ? extends T> function) {
524      this.fromList = checkNotNull(fromList);
525      this.function = checkNotNull(function);
526    }
527    /**
528     * The default implementation inherited is based on iteration and removal of
529     * each element which can be overkill. That's why we forward this call
530     * directly to the backing list.
531     */
532    @Override public void clear() {
533      fromList.clear();
534    }
535    @Override public int size() {
536      return fromList.size();
537    }
538    @Override public ListIterator<T> listIterator(final int index) {
539      return new TransformedListIterator<F, T>(fromList.listIterator(index)) {
540        @Override
541        T transform(F from) {
542          return function.apply(from);
543        }
544      };
545    }
546
547    private static final long serialVersionUID = 0;
548  }
549
550  /**
551   * Implementation of a transforming random access list. We try to make as many
552   * of these methods pass-through to the source list as possible so that the
553   * performance characteristics of the source list and transformed list are
554   * similar.
555   *
556   * @see Lists#transform
557   */
558  private static class TransformingRandomAccessList<F, T>
559      extends AbstractList<T> implements RandomAccess, Serializable {
560    final List<F> fromList;
561    final Function<? super F, ? extends T> function;
562
563    TransformingRandomAccessList(
564        List<F> fromList, Function<? super F, ? extends T> function) {
565      this.fromList = checkNotNull(fromList);
566      this.function = checkNotNull(function);
567    }
568    @Override public void clear() {
569      fromList.clear();
570    }
571    @Override public T get(int index) {
572      return function.apply(fromList.get(index));
573    }
574    @Override public boolean isEmpty() {
575      return fromList.isEmpty();
576    }
577    @Override public T remove(int index) {
578      return function.apply(fromList.remove(index));
579    }
580    @Override public int size() {
581      return fromList.size();
582    }
583    private static final long serialVersionUID = 0;
584  }
585
586  /**
587   * Returns consecutive {@linkplain List#subList(int, int) sublists} of a list,
588   * each of the same size (the final list may be smaller). For example,
589   * partitioning a list containing {@code [a, b, c, d, e]} with a partition
590   * size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer list containing
591   * two inner lists of three and two elements, all in the original order.
592   *
593   * <p>The outer list is unmodifiable, but reflects the latest state of the
594   * source list. The inner lists are sublist views of the original list,
595   * produced on demand using {@link List#subList(int, int)}, and are subject
596   * to all the usual caveats about modification as explained in that API.
597   *
598   * @param list the list to return consecutive sublists of
599   * @param size the desired size of each sublist (the last may be
600   *     smaller)
601   * @return a list of consecutive sublists
602   * @throws IllegalArgumentException if {@code partitionSize} is nonpositive
603   */
604  public static <T> List<List<T>> partition(List<T> list, int size) {
605    checkNotNull(list);
606    checkArgument(size > 0);
607    return (list instanceof RandomAccess)
608        ? new RandomAccessPartition<T>(list, size)
609        : new Partition<T>(list, size);
610  }
611
612  private static class Partition<T> extends AbstractList<List<T>> {
613    final List<T> list;
614    final int size;
615
616    Partition(List<T> list, int size) {
617      this.list = list;
618      this.size = size;
619    }
620
621    @Override public List<T> get(int index) {
622      checkElementIndex(index, size());
623      int start = index * size;
624      int end = Math.min(start + size, list.size());
625      return list.subList(start, end);
626    }
627
628    @Override public int size() {
629      return IntMath.divide(list.size(), size, RoundingMode.CEILING);
630    }
631
632    @Override public boolean isEmpty() {
633      return list.isEmpty();
634    }
635  }
636
637  private static class RandomAccessPartition<T> extends Partition<T>
638      implements RandomAccess {
639    RandomAccessPartition(List<T> list, int size) {
640      super(list, size);
641    }
642  }
643
644  /**
645   * Returns a view of the specified string as an immutable list of {@code
646   * Character} values.
647   *
648   * @since 7.0
649   */
650  @Beta public static ImmutableList<Character> charactersOf(String string) {
651    return new StringAsImmutableList(checkNotNull(string));
652  }
653
654  @SuppressWarnings("serial") // serialized using ImmutableList serialization
655  private static final class StringAsImmutableList
656      extends ImmutableList<Character> {
657
658    private final String string;
659
660    StringAsImmutableList(String string) {
661      this.string = string;
662    }
663
664    @Override public int indexOf(@Nullable Object object) {
665      return (object instanceof Character)
666          ? string.indexOf((Character) object) : -1;
667    }
668
669    @Override public int lastIndexOf(@Nullable Object object) {
670      return (object instanceof Character)
671          ? string.lastIndexOf((Character) object) : -1;
672    }
673
674    @Override public ImmutableList<Character> subList(
675        int fromIndex, int toIndex) {
676      checkPositionIndexes(fromIndex, toIndex, size()); // for GWT
677      return charactersOf(string.substring(fromIndex, toIndex));
678    }
679
680    @Override boolean isPartialView() {
681      return false;
682    }
683
684    @Override public Character get(int index) {
685      checkElementIndex(index, size()); // for GWT
686      return string.charAt(index);
687    }
688
689    @Override public int size() {
690      return string.length();
691    }
692  }
693
694  /**
695   * Returns a view of the specified {@code CharSequence} as a {@code
696   * List<Character>}, viewing {@code sequence} as a sequence of Unicode code
697   * units. The view does not support any modification operations, but reflects
698   * any changes to the underlying character sequence.
699   *
700   * @param sequence the character sequence to view as a {@code List} of
701   *        characters
702   * @return an {@code List<Character>} view of the character sequence
703   * @since 7.0
704   */
705  @Beta public static List<Character> charactersOf(CharSequence sequence) {
706    return new CharSequenceAsList(checkNotNull(sequence));
707  }
708
709  private static final class CharSequenceAsList
710      extends AbstractList<Character> {
711    private final CharSequence sequence;
712
713    CharSequenceAsList(CharSequence sequence) {
714      this.sequence = sequence;
715    }
716
717    @Override public Character get(int index) {
718      checkElementIndex(index, size()); // for GWT
719      return sequence.charAt(index);
720    }
721
722    @Override public int size() {
723      return sequence.length();
724    }
725  }
726
727  /**
728   * Returns a reversed view of the specified list. For example, {@code
729   * Lists.reverse(Arrays.asList(1, 2, 3))} returns a list containing {@code 3,
730   * 2, 1}. The returned list is backed by this list, so changes in the returned
731   * list are reflected in this list, and vice-versa. The returned list supports
732   * all of the optional list operations supported by this list.
733   *
734   * <p>The returned list is random-access if the specified list is random
735   * access.
736   *
737   * @since 7.0
738   */
739  public static <T> List<T> reverse(List<T> list) {
740    if (list instanceof ImmutableList) {
741      return ((ImmutableList<T>) list).reverse();
742    } else if (list instanceof ReverseList) {
743      return ((ReverseList<T>) list).getForwardList();
744    } else if (list instanceof RandomAccess) {
745      return new RandomAccessReverseList<T>(list);
746    } else {
747      return new ReverseList<T>(list);
748    }
749  }
750
751  private static class ReverseList<T> extends AbstractList<T> {
752    private final List<T> forwardList;
753
754    ReverseList(List<T> forwardList) {
755      this.forwardList = checkNotNull(forwardList);
756    }
757
758    List<T> getForwardList() {
759      return forwardList;
760    }
761
762    private int reverseIndex(int index) {
763      int size = size();
764      checkElementIndex(index, size);
765      return (size - 1) - index;
766    }
767
768    private int reversePosition(int index) {
769      int size = size();
770      checkPositionIndex(index, size);
771      return size - index;
772    }
773
774    @Override public void add(int index, @Nullable T element) {
775      forwardList.add(reversePosition(index), element);
776    }
777
778    @Override public void clear() {
779      forwardList.clear();
780    }
781
782    @Override public T remove(int index) {
783      return forwardList.remove(reverseIndex(index));
784    }
785
786    @Override protected void removeRange(int fromIndex, int toIndex) {
787      subList(fromIndex, toIndex).clear();
788    }
789
790    @Override public T set(int index, @Nullable T element) {
791      return forwardList.set(reverseIndex(index), element);
792    }
793
794    @Override public T get(int index) {
795      return forwardList.get(reverseIndex(index));
796    }
797
798    @Override public int size() {
799      return forwardList.size();
800    }
801
802    @Override public List<T> subList(int fromIndex, int toIndex) {
803      checkPositionIndexes(fromIndex, toIndex, size());
804      return reverse(forwardList.subList(
805          reversePosition(toIndex), reversePosition(fromIndex)));
806    }
807
808    @Override public Iterator<T> iterator() {
809      return listIterator();
810    }
811
812    @Override public ListIterator<T> listIterator(int index) {
813      int start = reversePosition(index);
814      final ListIterator<T> forwardIterator = forwardList.listIterator(start);
815      return new ListIterator<T>() {
816
817        boolean canRemoveOrSet;
818
819        @Override public void add(T e) {
820          forwardIterator.add(e);
821          forwardIterator.previous();
822          canRemoveOrSet = false;
823        }
824
825        @Override public boolean hasNext() {
826          return forwardIterator.hasPrevious();
827        }
828
829        @Override public boolean hasPrevious() {
830          return forwardIterator.hasNext();
831        }
832
833        @Override public T next() {
834          if (!hasNext()) {
835            throw new NoSuchElementException();
836          }
837          canRemoveOrSet = true;
838          return forwardIterator.previous();
839        }
840
841        @Override public int nextIndex() {
842          return reversePosition(forwardIterator.nextIndex());
843        }
844
845        @Override public T previous() {
846          if (!hasPrevious()) {
847            throw new NoSuchElementException();
848          }
849          canRemoveOrSet = true;
850          return forwardIterator.next();
851        }
852
853        @Override public int previousIndex() {
854          return nextIndex() - 1;
855        }
856
857        @Override public void remove() {
858          checkRemove(canRemoveOrSet);
859          forwardIterator.remove();
860          canRemoveOrSet = false;
861        }
862
863        @Override public void set(T e) {
864          checkState(canRemoveOrSet);
865          forwardIterator.set(e);
866        }
867      };
868    }
869  }
870
871  private static class RandomAccessReverseList<T> extends ReverseList<T>
872      implements RandomAccess {
873    RandomAccessReverseList(List<T> forwardList) {
874      super(forwardList);
875    }
876  }
877
878  /**
879   * An implementation of {@link List#hashCode()}.
880   */
881  static int hashCodeImpl(List<?> list) {
882    // TODO(user): worth optimizing for RandomAccess?
883    int hashCode = 1;
884    for (Object o : list) {
885      hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode());
886
887      hashCode = ~~hashCode;
888      // needed to deal with GWT integer overflow
889    }
890    return hashCode;
891  }
892
893  /**
894   * An implementation of {@link List#equals(Object)}.
895   */
896  static boolean equalsImpl(List<?> list, @Nullable Object object) {
897    if (object == checkNotNull(list)) {
898      return true;
899    }
900    if (!(object instanceof List)) {
901      return false;
902    }
903
904    List<?> o = (List<?>) object;
905
906    return list.size() == o.size()
907        && Iterators.elementsEqual(list.iterator(), o.iterator());
908  }
909
910  /**
911   * An implementation of {@link List#addAll(int, Collection)}.
912   */
913  static <E> boolean addAllImpl(
914      List<E> list, int index, Iterable<? extends E> elements) {
915    boolean changed = false;
916    ListIterator<E> listIterator = list.listIterator(index);
917    for (E e : elements) {
918      listIterator.add(e);
919      changed = true;
920    }
921    return changed;
922  }
923
924  /**
925   * An implementation of {@link List#indexOf(Object)}.
926   */
927  static int indexOfImpl(List<?> list, @Nullable Object element) {
928    ListIterator<?> listIterator = list.listIterator();
929    while (listIterator.hasNext()) {
930      if (Objects.equal(element, listIterator.next())) {
931        return listIterator.previousIndex();
932      }
933    }
934    return -1;
935  }
936
937  /**
938   * An implementation of {@link List#lastIndexOf(Object)}.
939   */
940  static int lastIndexOfImpl(List<?> list, @Nullable Object element) {
941    ListIterator<?> listIterator = list.listIterator(list.size());
942    while (listIterator.hasPrevious()) {
943      if (Objects.equal(element, listIterator.previous())) {
944        return listIterator.nextIndex();
945      }
946    }
947    return -1;
948  }
949
950  /**
951   * Returns an implementation of {@link List#listIterator(int)}.
952   */
953  static <E> ListIterator<E> listIteratorImpl(List<E> list, int index) {
954    return new AbstractListWrapper<E>(list).listIterator(index);
955  }
956
957  /**
958   * An implementation of {@link List#subList(int, int)}.
959   */
960  static <E> List<E> subListImpl(
961      final List<E> list, int fromIndex, int toIndex) {
962    List<E> wrapper;
963    if (list instanceof RandomAccess) {
964      wrapper = new RandomAccessListWrapper<E>(list) {
965        @Override public ListIterator<E> listIterator(int index) {
966          return backingList.listIterator(index);
967        }
968
969        private static final long serialVersionUID = 0;
970      };
971    } else {
972      wrapper = new AbstractListWrapper<E>(list) {
973        @Override public ListIterator<E> listIterator(int index) {
974          return backingList.listIterator(index);
975        }
976
977        private static final long serialVersionUID = 0;
978      };
979    }
980    return wrapper.subList(fromIndex, toIndex);
981  }
982
983  private static class AbstractListWrapper<E> extends AbstractList<E> {
984    final List<E> backingList;
985
986    AbstractListWrapper(List<E> backingList) {
987      this.backingList = checkNotNull(backingList);
988    }
989
990    @Override public void add(int index, E element) {
991      backingList.add(index, element);
992    }
993
994    @Override public boolean addAll(int index, Collection<? extends E> c) {
995      return backingList.addAll(index, c);
996    }
997
998    @Override public E get(int index) {
999      return backingList.get(index);
1000    }
1001
1002    @Override public E remove(int index) {
1003      return backingList.remove(index);
1004    }
1005
1006    @Override public E set(int index, E element) {
1007      return backingList.set(index, element);
1008    }
1009
1010    @Override public boolean contains(Object o) {
1011      return backingList.contains(o);
1012    }
1013
1014    @Override public int size() {
1015      return backingList.size();
1016    }
1017  }
1018
1019  private static class RandomAccessListWrapper<E>
1020      extends AbstractListWrapper<E> implements RandomAccess {
1021    RandomAccessListWrapper(List<E> backingList) {
1022      super(backingList);
1023    }
1024  }
1025
1026  /**
1027   * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
1028   */
1029  static <T> List<T> cast(Iterable<T> iterable) {
1030    return (List<T>) iterable;
1031  }
1032}