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