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