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