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