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