Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Copyright (C) 2007 The Guava Authors
    *
    * Licensed under the Apache License, Version 2.0 (the "License");
    * you may not use this file except in compliance with the License.
    * You may obtain a copy of the License at
    *
    * http://www.apache.org/licenses/LICENSE-2.0
    *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  package com.google.common.collect;
  
  import static com.google.common.base.Preconditions.checkArgument;
  import static com.google.common.base.Preconditions.checkElementIndex;
  import static com.google.common.base.Preconditions.checkNotNull;
  import static com.google.common.base.Preconditions.checkPositionIndex;
  import static com.google.common.base.Preconditions.checkPositionIndexes;
  import static com.google.common.base.Preconditions.checkState;
  
  
  import java.util.Arrays;
  import java.util.List;
  
  import  javax.annotation.Nullable;

Static utility methods pertaining to List instances. Also see this class's counterparts Sets and Maps.

See the Guava User Guide article on Lists.

Author(s):
Kevin Bourrillion
Mike Bostock
Louis Wasserman
Since:
2.0 (imported from Google Collections Library)
  
  @GwtCompatible(emulated = true)
  public final class Lists {
    private Lists() {}
  
    // ArrayList
  
  
Creates a mutable, empty ArrayList instance.

Note: if mutability is not required, use ImmutableList.of() instead.

Returns:
a new, empty ArrayList
  
    @GwtCompatible(serializable = true)
    public static <E> ArrayList<E> newArrayList() {
      return new ArrayList<E>();
    }

  
Creates a mutable ArrayList instance containing the given elements.

Note: if mutability is not required and the elements are non-null, use an overload of ImmutableList.of() (for varargs) or ImmutableList.copyOf(Object[]) (for an array) instead.

Parameters:
elements the elements that the list should contain, in order
Returns:
a new ArrayList containing those elements
  
    @GwtCompatible(serializable = true)
    public static <E> ArrayList<E> newArrayList(E... elements) {
      checkNotNull(elements); // for GWT
      // Avoid integer overflow when a large array is passed in
      int capacity = computeArrayListCapacity(elements.length);
      ArrayList<E> list = new ArrayList<E>(capacity);
     Collections.addAll(listelements);
     return list;
   }
 
   @VisibleForTesting static int computeArrayListCapacity(int arraySize) {
     checkArgument(arraySize >= 0);
 
     // TODO(kevinb): Figure out the right behavior, and document it
     return Ints.saturatedCast(5L + arraySize + (arraySize / 10));
   }

  
Creates a mutable ArrayList instance containing the given elements.

Note: if mutability is not required and the elements are non-null, use ImmutableList.copyOf(Iterator) instead.

Parameters:
elements the elements that the list should contain, in order
Returns:
a new ArrayList containing those elements
 
   @GwtCompatible(serializable = true)
   public static <E> ArrayList<E> newArrayList(Iterable<? extends E> elements) {
     checkNotNull(elements); // for GWT
     // Let ArrayList's sizing logic work, if possible
     return (elements instanceof Collection)
         ? new ArrayList<E>(Collections2.cast(elements))
         : newArrayList(elements.iterator());
   }

  
Creates a mutable ArrayList instance containing the given elements.

Note: if mutability is not required and the elements are non-null, use ImmutableList.copyOf(Iterator) instead.

Parameters:
elements the elements that the list should contain, in order
Returns:
a new ArrayList containing those elements
 
   @GwtCompatible(serializable = true)
   public static <E> ArrayList<E> newArrayList(Iterator<? extends E> elements) {
     checkNotNull(elements); // for GWT
     ArrayList<E> list = newArrayList();
     while (elements.hasNext()) {
       list.add(elements.next());
     }
     return list;
   }

  
Creates an ArrayList instance backed by an array of the exact size specified; equivalent to ArrayList.ArrayList(int).

Note: if you know the exact size your list will be, consider using a fixed-size list (Arrays.asList(Object[])) or an ImmutableList instead of a growable ArrayList.

Note: If you have only an estimate of the eventual size of the list, consider padding this estimate by a suitable amount, or simply use newArrayListWithExpectedSize(int) instead.

Parameters:
initialArraySize the exact size of the initial backing array for the returned array list (ArrayList documentation calls this value the "capacity")
Returns:
a new, empty ArrayList which is guaranteed not to resize itself unless its size reaches initialArraySize + 1
Throws:
IllegalArgumentException if initialArraySize is negative
 
   @GwtCompatible(serializable = true)
   public static <E> ArrayList<E> newArrayListWithCapacity(
       int initialArraySize) {
     checkArgument(initialArraySize >= 0);  // for GWT.
     return new ArrayList<E>(initialArraySize);
   }

  
Creates an ArrayList instance sized appropriately to hold an estimated number of elements without resizing. A small amount of padding is added in case the estimate is low.

Note: If you know the exact number of elements the list will hold, or prefer to calculate your own amount of padding, refer to newArrayListWithCapacity(int).

Parameters:
estimatedSize an estimate of the eventual List.size() of the new list
Returns:
a new, empty ArrayList, sized appropriately to hold the estimated number of elements
Throws:
IllegalArgumentException if estimatedSize is negative
 
   @GwtCompatible(serializable = true)
   public static <E> ArrayList<E> newArrayListWithExpectedSize(
       int estimatedSize) {
     return new ArrayList<E>(computeArrayListCapacity(estimatedSize));
   }
 
   // LinkedList
 
  
Creates an empty LinkedList instance.

Note: if you need an immutable empty List, use ImmutableList.of() instead.

Returns:
a new, empty LinkedList
 
   @GwtCompatible(serializable = true)
   public static <E> LinkedList<E> newLinkedList() {
     return new LinkedList<E>();
   }

  
Creates a LinkedList instance containing the given elements.

Parameters:
elements the elements that the list should contain, in order
Returns:
a new LinkedList containing those elements
 
   @GwtCompatible(serializable = true)
   public static <E> LinkedList<E> newLinkedList(
       Iterable<? extends E> elements) {
     LinkedList<E> list = newLinkedList();
     for (E element : elements) {
       list.add(element);
     }
     return list;
   }

  
Creates an empty CopyOnWriteArrayList instance.

Note: if you need an immutable empty List, use Collections.emptyList instead.

Returns:
a new, empty CopyOnWriteArrayList
Since:
12.0
 
   @GwtIncompatible("CopyOnWriteArrayList")
   public static <E> CopyOnWriteArrayList<E> newCopyOnWriteArrayList() {
     return new CopyOnWriteArrayList<E>();
   }

  
Creates a CopyOnWriteArrayList instance containing the given elements.

Parameters:
elements the elements that the list should contain, in order
Returns:
a new CopyOnWriteArrayList containing those elements
Since:
12.0
 
   @GwtIncompatible("CopyOnWriteArrayList")
   public static <E> CopyOnWriteArrayList<E> newCopyOnWriteArrayList(
       Iterable<? extends E> elements) {
     // We copy elements to an ArrayList first, rather than incurring the
     // quadratic cost of adding them to the COWAL directly.
     Collection<? extends E> elementsCollection = (elements instanceof Collection)
         ? Collections2.cast(elements)
         : newArrayList(elements);
     return new CopyOnWriteArrayList<E>(elementsCollection);
   }

  
Returns an unmodifiable list containing the specified first element and backed by the specified array of additional elements. Changes to the rest array will be reflected in the returned list. Unlike Arrays.asList, the returned list is unmodifiable.

This is useful when a varargs method needs to use a signature such as (Foo firstFoo, Foo... moreFoos), in order to avoid overload ambiguity or to enforce a minimum argument count.

The returned list is serializable and implements RandomAccess.

Parameters:
first the first element
rest an array of additional elements, possibly empty
Returns:
an unmodifiable list containing the specified elements
 
   public static <E> List<E> asList(@Nullable E first, E[] rest) {
     return new OnePlusArrayList<E>(firstrest);
   }

  

See also:
Lists.asList(Object, Object[])
 
   private static class OnePlusArrayList<E> extends AbstractList<E>
       implements SerializableRandomAccess {
     final E first;
     final E[] rest;
 
     OnePlusArrayList(@Nullable E first, E[] rest) {
       this. = first;
       this. = checkNotNull(rest);
     }
     @Override public int size() {
       return . + 1;
     }
     @Override public E get(int index) {
       // check explicitly so the IOOBE will have the right message
       checkElementIndex(indexsize());
       return (index == 0) ?  : [index - 1];
     }
     private static final long serialVersionUID = 0;
   }

  
Returns an unmodifiable list containing the specified first and second element, and backed by the specified array of additional elements. Changes to the rest array will be reflected in the returned list. Unlike Arrays.asList, the returned list is unmodifiable.

This is useful when a varargs method needs to use a signature such as (Foo firstFoo, Foo secondFoo, Foo... moreFoos), in order to avoid overload ambiguity or to enforce a minimum argument count.

The returned list is serializable and implements RandomAccess.

Parameters:
first the first element
second the second element
rest an array of additional elements, possibly empty
Returns:
an unmodifiable list containing the specified elements
 
   public static <E> List<E> asList(
       @Nullable E first, @Nullable E second, E[] rest) {
     return new TwoPlusArrayList<E>(firstsecondrest);
   }

  

See also:
Lists.asList(Object, Object, Object[])
 
   private static class TwoPlusArrayList<E> extends AbstractList<E>
       implements SerializableRandomAccess {
     final E first;
     final E second;
     final E[] rest;
 
     TwoPlusArrayList(@Nullable E first, @Nullable E second, E[] rest) {
       this. = first;
       this. = second;
       this. = checkNotNull(rest);
     }
     @Override public int size() {
       return . + 2;
     }
     @Override public E get(int index) {
       switch (index) {
         case 0:
           return ;
         case 1:
           return ;
         default:
           // check explicitly so the IOOBE will have the right message
           checkElementIndex(indexsize());
           return [index - 2];
       }
     }
     private static final long serialVersionUID = 0;
   }

  
Returns a list that applies function to each element of fromList. The returned list is a transformed view of fromList; changes to fromList will be reflected in the returned list and vice versa.

Since functions are not reversible, the transform is one-way and new items cannot be stored in the returned list. The add, addAll and set methods are unsupported in the returned list.

The function is applied lazily, invoked when needed. This is necessary for the returned list to be a view, but it means that the function will be applied many times for bulk operations like List.contains and List.hashCode. For this to perform well, function should be fast. To avoid lazy evaluation when the returned list doesn't need to be a view, copy the returned list into a new list of your choosing.

If fromList implements RandomAccess, so will the returned list. The returned list is threadsafe if the supplied list and function are.

If only a Collection or Iterable input is available, use Collections2.transform or Iterables.transform.

Note: serializing the returned list is implemented by serializing fromList, its contents, and function -- not by serializing the transformed values. This can lead to surprising behavior, so serializing the returned list is not recommended. Instead, copy the list using ImmutableList.copyOf(Collection) (for example), then serialize the copy. Other methods similar to this do not implement serialization at all for this reason.

 
   public static <F, T> List<T> transform(
       List<F> fromListFunction<? super F, ? extends T> function) {
     return (fromList instanceof RandomAccess)
         ? new TransformingRandomAccessList<F, T>(fromListfunction)
         : new TransformingSequentialList<F, T>(fromListfunction);
   }

  
Implementation of a sequential transforming list.

See also:
Lists.transform
 
   private static class TransformingSequentialList<F, T>
       extends AbstractSequentialList<T> implements Serializable {
     final List<F> fromList;
     final Function<? super F, ? extends T> function;
 
         List<F> fromListFunction<? super F, ? extends T> function) {
       this. = checkNotNull(fromList);
       this. = checkNotNull(function);
     }
    
The default implementation inherited is based on iteration and removal of each element which can be overkill. That's why we forward this call directly to the backing list.
 
     @Override public void clear() {
       .clear();
     }
     @Override public int size() {
       return .size();
     }
     @Override public ListIterator<T> listIterator(final int index) {
       final ListIterator<F> delegate = .listIterator(index);
       return new ListIterator<T>() {
         @Override
         public void add(T e) {
           throw new UnsupportedOperationException();
         }
 
         @Override
         public boolean hasNext() {
           return delegate.hasNext();
         }
 
         @Override
         public boolean hasPrevious() {
           return delegate.hasPrevious();
         }
 
         @Override
         public T next() {
           return .apply(delegate.next());
         }
 
         @Override
         public int nextIndex() {
           return delegate.nextIndex();
         }
 
         @Override
         public T previous() {
           return .apply(delegate.previous());
         }
 
         @Override
         public int previousIndex() {
           return delegate.previousIndex();
         }
 
         @Override
         public void remove() {
           delegate.remove();
         }
 
         @Override
         public void set(T e) {
           throw new UnsupportedOperationException("not supported");
         }
       };
     }
 
     private static final long serialVersionUID = 0;
   }

  
Implementation of a transforming random access list. We try to make as many of these methods pass-through to the source list as possible so that the performance characteristics of the source list and transformed list are similar.

See also:
Lists.transform
 
   private static class TransformingRandomAccessList<F, T>
       extends AbstractList<T> implements RandomAccessSerializable {
     final List<F> fromList;
     final Function<? super F, ? extends T> function;
 
         List<F> fromListFunction<? super F, ? extends T> function) {
       this. = checkNotNull(fromList);
       this. = checkNotNull(function);
     }
     @Override public void clear() {
       .clear();
     }
     @Override public T get(int index) {
       return .apply(.get(index));
     }
     @Override public boolean isEmpty() {
       return .isEmpty();
     }
     @Override public T remove(int index) {
       return .apply(.remove(index));
     }
     @Override public int size() {
       return .size();
     }
     private static final long serialVersionUID = 0;
   }

  
Returns consecutive sublists of a list, each of the same size (the final list may be smaller). For example, partitioning a list containing [a, b, c, d, e] with a partition size of 3 yields [[a, b, c], [d, e]] -- an outer list containing two inner lists of three and two elements, all in the original order.

The outer list is unmodifiable, but reflects the latest state of the source list. The inner lists are sublist views of the original list, produced on demand using List.subList(int, int), and are subject to all the usual caveats about modification as explained in that API.

Parameters:
list the list to return consecutive sublists of
size the desired size of each sublist (the last may be smaller)
Returns:
a list of consecutive sublists
Throws:
IllegalArgumentException if partitionSize is nonpositive
 
   public static <T> List<List<T>> partition(List<T> listint size) {
     checkNotNull(list);
     checkArgument(size > 0);
     return (list instanceof RandomAccess)
         ? new RandomAccessPartition<T>(listsize)
         : new Partition<T>(listsize);
   }
 
   private static class Partition<T> extends AbstractList<List<T>> {
     final List<T> list;
     final int size;
 
     Partition(List<T> listint size) {
       this. = list;
       this. = size;
     }
 
     @Override public List<T> get(int index) {
       int listSize = size();
       checkElementIndex(indexlistSize);
       int start = index * ;
       int end = Math.min(start + .size());
       return .subList(startend);
     }
 
     @Override public int size() {
       // TODO(user): refactor to common.math.IntMath.divide
       int result = .size() / ;
       if (result *  != .size()) {
         result++;
       }
       return result;
     }
 
     @Override public boolean isEmpty() {
       return .isEmpty();
     }
   }
 
   private static class RandomAccessPartition<T> extends Partition<T>
       implements RandomAccess {
     RandomAccessPartition(List<T> listint size) {
       super(listsize);
     }
   }

  
Returns a view of the specified string as an immutable list of Character values.

Since:
7.0
 
   @Beta public static ImmutableList<CharactercharactersOf(String string) {
     return new StringAsImmutableList(checkNotNull(string));
   }
 
   @SuppressWarnings("serial"// serialized using ImmutableList serialization
   private static final class StringAsImmutableList
       extends ImmutableList<Character> {
 
     private final String string;
 
     StringAsImmutableList(String string) {
       this. = string;
     }
 
     @Override public int indexOf(@Nullable Object object) {
       return (object instanceof Character)
           ? .indexOf((Characterobject) : -1;
     }
 
     @Override public int lastIndexOf(@Nullable Object object) {
       return (object instanceof Character)
           ? .lastIndexOf((Characterobject) : -1;
     }
 
         int fromIndexint toIndex) {
       checkPositionIndexes(fromIndextoIndexsize()); // for GWT
       return charactersOf(.substring(fromIndextoIndex));
     }
 
     @Override boolean isPartialView() {
       return false;
     }
 
     @Override public Character get(int index) {
       checkElementIndex(indexsize()); // for GWT
       return .charAt(index);
     }
 
     @Override public int size() {
       return .length();
     }
 
     @Override public boolean equals(@Nullable Object obj) {
       if (!(obj instanceof List)) {
         return false;
       }
       List<?> list = (List<?>) obj;
       int n = .length();
       if (n != list.size()) {
         return false;
       }
       Iterator<?> iterator = list.iterator();
       for (int i = 0; i < ni++) {
         Object elem = iterator.next();
         if (!(elem instanceof Character)
             || ((Characterelem).charValue() != .charAt(i)) {
           return false;
         }
       }
       return true;
     }
 
     int hash = 0;
 
     @Override public int hashCode() {
       int h = ;
       if (h == 0) {
         h = 1;
         for (int i = 0; i < .length(); i++) {
           h = h * 31 + .charAt(i);
         }
          = h;
       }
       return h;
     }
   }

  
Returns a view of the specified CharSequence as a List<Character>, viewing sequence as a sequence of Unicode code units. The view does not support any modification operations, but reflects any changes to the underlying character sequence.

Parameters:
sequence the character sequence to view as a List of characters
Returns:
an List<Character> view of the character sequence
Since:
7.0
 
   @Beta public static List<CharactercharactersOf(CharSequence sequence) {
     return new CharSequenceAsList(checkNotNull(sequence));
   }
 
   private static final class CharSequenceAsList
       extends AbstractList<Character> {
     private final CharSequence sequence;
 
     CharSequenceAsList(CharSequence sequence) {
       this. = sequence;
     }
 
     @Override public Character get(int index) {
       checkElementIndex(indexsize()); // for GWT
       return .charAt(index);
     }
 
     @Override public boolean contains(@Nullable Object o) {
       return indexOf(o) >= 0;
     }
 
     @Override public int indexOf(@Nullable Object o) {
       if (o instanceof Character) {
         char c = (Charactero;
         for (int i = 0; i < .length(); i++) {
           if (.charAt(i) == c) {
             return i;
           }
         }
       }
       return -1;
     }
 
     @Override public int lastIndexOf(@Nullable Object o) {
       if (o instanceof Character) {
         char c = ((Charactero).charValue();
         for (int i = .length() - 1; i >= 0; i--) {
           if (.charAt(i) == c) {
             return i;
           }
         }
       }
       return -1;
     }
 
     @Override public int size() {
       return .length();
     }
 
     @Override public List<CharactersubList(int fromIndexint toIndex) {
       checkPositionIndexes(fromIndextoIndexsize()); // for GWT
       return charactersOf(.subSequence(fromIndextoIndex));
     }
 
     @Override public int hashCode() {
       int hash = 1;
       for (int i = 0; i < .length(); i++) {
         hash = hash * 31 + .charAt(i);
       }
       return hash;
     }
 
     @Override public boolean equals(@Nullable Object o) {
       if (!(o instanceof List)) {
         return false;
       }
       List<?> list = (List<?>) o;
       int n = .length();
       if (n != list.size()) {
         return false;
       }
       Iterator<?> iterator = list.iterator();
       for (int i = 0; i < ni++) {
         Object elem = iterator.next();
         if (!(elem instanceof Character)
             || ((Characterelem).charValue() != .charAt(i)) {
           return false;
         }
       }
       return true;
     }
   }

  
Returns a reversed view of the specified list. For example, Lists.reverse(Arrays.asList(1, 2, 3)) returns a list containing 3, 2, 1. The returned list is backed by this list, so changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.

The returned list is random-access if the specified list is random access.

Since:
7.0
 
   public static <T> List<T> reverse(List<T> list) {
     if (list instanceof ReverseList) {
       return ((ReverseList<T>) list).getForwardList();
     } else if (list instanceof RandomAccess) {
       return new RandomAccessReverseList<T>(list);
     } else {
       return new ReverseList<T>(list);
     }
   }
 
   private static class ReverseList<T> extends AbstractList<T> {
     private final List<T> forwardList;
 
     ReverseList(List<T> forwardList) {
       this. = checkNotNull(forwardList);
     }
 
     List<T> getForwardList() {
       return ;
     }
 
     private int reverseIndex(int index) {
       int size = size();
       checkElementIndex(indexsize);
       return (size - 1) - index;
     }
 
     private int reversePosition(int index) {
       int size = size();
       checkPositionIndex(indexsize);
       return size - index;
     }
 
     @Override public void add(int index, @Nullable T element) {
       .add(reversePosition(index), element);
     }
 
     @Override public void clear() {
       .clear();
     }
 
     @Override public T remove(int index) {
       return .remove(reverseIndex(index));
     }
 
     @Override protected void removeRange(int fromIndexint toIndex) {
       subList(fromIndextoIndex).clear();
     }
 
     @Override public T set(int index, @Nullable T element) {
       return .set(reverseIndex(index), element);
     }
 
     @Override public T get(int index) {
       return .get(reverseIndex(index));
     }
 
     @Override public boolean isEmpty() {
       return .isEmpty();
     }
 
     @Override public int size() {
       return .size();
     }
 
     @Override public boolean contains(@Nullable Object o) {
       return .contains(o);
     }
 
     @Override public boolean containsAll(Collection<?> c) {
       return .containsAll(c);
     }
 
     @Override public List<T> subList(int fromIndexint toIndex) {
       checkPositionIndexes(fromIndextoIndexsize());
       return reverse(.subList(
           reversePosition(toIndex), reversePosition(fromIndex)));
     }
 
     @Override public int indexOf(@Nullable Object o) {
       int index = .lastIndexOf(o);
       return (index >= 0) ? reverseIndex(index) : -1;
     }
 
     @Override public int lastIndexOf(@Nullable Object o) {
       int index = .indexOf(o);
       return (index >= 0) ? reverseIndex(index) : -1;
     }
 
     @Override public Iterator<T> iterator() {
       return listIterator();
     }
 
     @Override public ListIterator<T> listIterator(int index) {
       int start = reversePosition(index);
       final ListIterator<T> forwardIterator = .listIterator(start);
       return new ListIterator<T>() {
 
         boolean canRemove;
         boolean canSet;
 
         @Override public void add(T e) {
           forwardIterator.add(e);
           forwardIterator.previous();
            =  = false;
         }
 
         @Override public boolean hasNext() {
           return forwardIterator.hasPrevious();
         }
 
         @Override public boolean hasPrevious() {
           return forwardIterator.hasNext();
         }
 
         @Override public T next() {
           if (!hasNext()) {
             throw new NoSuchElementException();
           }
            =  = true;
           return forwardIterator.previous();
         }
 
         @Override public int nextIndex() {
           return reversePosition(forwardIterator.nextIndex());
         }
 
         @Override public T previous() {
           if (!hasPrevious()) {
             throw new NoSuchElementException();
           }
            =  = true;
           return forwardIterator.next();
         }
 
         @Override public int previousIndex() {
           return nextIndex() - 1;
         }
 
         @Override public void remove() {
           checkState();
           forwardIterator.remove();
            =  = false;
         }
 
         @Override public void set(T e) {
           checkState();
           forwardIterator.set(e);
         }
       };
     }
   }
 
   private static class RandomAccessReverseList<T> extends ReverseList<T>
       implements RandomAccess {
     RandomAccessReverseList(List<T> forwardList) {
       super(forwardList);
     }
   }

  
An implementation of List.hashCode().
 
   static int hashCodeImpl(List<?> list){
     int hashCode = 1;
     for (Object o : list) {
       hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode());
     }
     return hashCode;
   }

  
An implementation of List.equals(Object).
 
   static boolean equalsImpl(List<?> list, @Nullable Object object) {
     if (object == checkNotNull(list)) {
       return true;
     }
     if (!(object instanceof List)) {
       return false;
     }
 
     List<?> o = (List<?>) object;
 
     return list.size() == o.size()
         && Iterators.elementsEqual(list.iterator(), o.iterator());
   }

  
An implementation of List.addAll(int, Collection).
 
   static <E> boolean addAllImpl(
       List<E> listint indexIterable<? extends E> elements) {
     boolean changed = false;
     ListIterator<E> listIterator = list.listIterator(index);
     for (E e : elements) {
       listIterator.add(e);
       changed = true;
     }
     return changed;
   }

  
An implementation of List.indexOf(Object).
 
   static int indexOfImpl(List<?> list, @Nullable Object element){
     ListIterator<?> listIterator = list.listIterator();
     while (listIterator.hasNext()) {
       if (Objects.equal(elementlistIterator.next())) {
         return listIterator.previousIndex();
       }
     }
     return -1;
   }

  
An implementation of List.lastIndexOf(Object).
 
   static int lastIndexOfImpl(List<?> list, @Nullable Object element){
     ListIterator<?> listIterator = list.listIterator(list.size());
     while (listIterator.hasPrevious()) {
       if (Objects.equal(elementlistIterator.previous())) {
         return listIterator.nextIndex();
       }
     }
     return -1;
   }

  
Returns an implementation of List.listIterator(int).
 
   static <E> ListIterator<E> listIteratorImpl(List<E> listint index) {
     return new AbstractListWrapper<E>(list).listIterator(index);
   }

  
An implementation of List.subList(int, int).
  static <E> List<E> subListImpl(
      final List<E> listint fromIndexint toIndex) {
    List<E> wrapper;
    if (list instanceof RandomAccess) {
      wrapper = new RandomAccessListWrapper<E>(list) {
        @Override public ListIterator<E> listIterator(int index) {
          return .listIterator(index);
        }
        private static final long serialVersionUID = 0;
      };
    } else {
      wrapper = new AbstractListWrapper<E>(list) {
        @Override public ListIterator<E> listIterator(int index) {
          return .listIterator(index);
        }
        private static final long serialVersionUID = 0;
      };
    }
    return wrapper.subList(fromIndextoIndex);
  }
  private static class AbstractListWrapper<E> extends AbstractList<E> {
    final List<E> backingList;
    AbstractListWrapper(List<E> backingList) {
      this. = checkNotNull(backingList);
    }
    @Override public void add(int index, E element) {
      .add(indexelement);
    }
    @Override public boolean addAll(int indexCollection<? extends E> c) {
      return .addAll(indexc);
    }
    @Override public E get(int index) {
      return .get(index);
    }
    @Override public E remove(int index) {
      return .remove(index);
    }
    @Override public E set(int index, E element) {
      return .set(indexelement);
    }
    @Override public boolean contains(Object o) {
      return .contains(o);
    }
    @Override public int size() {
      return .size();
    }
  }
  private static class RandomAccessListWrapper<E>
      extends AbstractListWrapper<E> implements RandomAccess {
    RandomAccessListWrapper(List<E> backingList) {
      super(backingList);
    }
  }

  
Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
  static <T> List<T> cast(Iterable<T> iterable) {
    return (List<T>) iterable;
  }