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