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