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