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