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