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