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