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