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.checkNotNull;
021import static com.google.common.base.Preconditions.checkState;
022import static com.google.common.base.Predicates.instanceOf;
023import static com.google.common.collect.CollectPreconditions.checkRemove;
024
025import com.google.common.annotations.Beta;
026import com.google.common.annotations.GwtCompatible;
027import com.google.common.annotations.GwtIncompatible;
028import com.google.common.base.Function;
029import com.google.common.base.Objects;
030import com.google.common.base.Optional;
031import com.google.common.base.Preconditions;
032import com.google.common.base.Predicate;
033import com.google.common.primitives.Ints;
034import com.google.errorprone.annotations.CanIgnoreReturnValue;
035import java.util.ArrayDeque;
036import java.util.Arrays;
037import java.util.Collection;
038import java.util.Collections;
039import java.util.Comparator;
040import java.util.Deque;
041import java.util.Enumeration;
042import java.util.Iterator;
043import java.util.List;
044import java.util.ListIterator;
045import java.util.NoSuchElementException;
046import java.util.PriorityQueue;
047import java.util.Queue;
048import javax.annotation.Nullable;
049
050/**
051 * This class contains static utility methods that operate on or return objects
052 * of type {@link Iterator}. Except as noted, each method has a corresponding
053 * {@link Iterable}-based method in the {@link Iterables} class.
054 *
055 * <p><i>Performance notes:</i> Unless otherwise noted, all of the iterators
056 * produced in this class are <i>lazy</i>, which means that they only advance
057 * the backing iteration when absolutely necessary.
058 *
059 * <p>See the Guava User Guide section on <a href=
060 * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#iterables">
061 * {@code Iterators}</a>.
062 *
063 * @author Kevin Bourrillion
064 * @author Jared Levy
065 * @since 2.0
066 */
067@GwtCompatible(emulated = true)
068public final class Iterators {
069  private Iterators() {}
070
071  /**
072   * Returns the empty iterator.
073   *
074   * <p>The {@link Iterable} equivalent of this method is {@link
075   * ImmutableSet#of()}.
076   */
077  static <T> UnmodifiableIterator<T> emptyIterator() {
078    return emptyListIterator();
079  }
080
081  /**
082   * Returns the empty iterator.
083   *
084   * <p>The {@link Iterable} equivalent of this method is {@link
085   * ImmutableSet#of()}.
086   */
087  // Casting to any type is safe since there are no actual elements.
088  @SuppressWarnings("unchecked")
089  static <T> UnmodifiableListIterator<T> emptyListIterator() {
090    return (UnmodifiableListIterator<T>) ArrayItr.EMPTY;
091  }
092
093  /**
094   * This is an enum singleton rather than an anonymous class so ProGuard can figure out it's only
095   * referenced by emptyModifiableIterator().
096   */
097  private enum EmptyModifiableIterator implements Iterator<Object> {
098    INSTANCE;
099
100    @Override
101    public boolean hasNext() {
102      return false;
103    }
104
105    @Override
106    public Object next() {
107      throw new NoSuchElementException();
108    }
109
110    @Override
111    public void remove() {
112      checkRemove(false);
113    }
114  }
115
116  /**
117   * Returns the empty {@code Iterator} that throws
118   * {@link IllegalStateException} instead of
119   * {@link UnsupportedOperationException} on a call to
120   * {@link Iterator#remove()}.
121   */
122  // Casting to any type is safe since there are no actual elements.
123  @SuppressWarnings("unchecked")
124  static <T> Iterator<T> emptyModifiableIterator() {
125    return (Iterator<T>) EmptyModifiableIterator.INSTANCE;
126  }
127
128  /** Returns an unmodifiable view of {@code iterator}. */
129  public static <T> UnmodifiableIterator<T> unmodifiableIterator(
130      final Iterator<? extends T> iterator) {
131    checkNotNull(iterator);
132    if (iterator instanceof UnmodifiableIterator) {
133      @SuppressWarnings("unchecked") // Since it's unmodifiable, the covariant cast is safe
134      UnmodifiableIterator<T> result = (UnmodifiableIterator<T>) iterator;
135      return result;
136    }
137    return new UnmodifiableIterator<T>() {
138      @Override
139      public boolean hasNext() {
140        return iterator.hasNext();
141      }
142
143      @Override
144      public T next() {
145        return iterator.next();
146      }
147    };
148  }
149
150  /**
151   * Simply returns its argument.
152   *
153   * @deprecated no need to use this
154   * @since 10.0
155   */
156  @Deprecated
157  public static <T> UnmodifiableIterator<T> unmodifiableIterator(UnmodifiableIterator<T> iterator) {
158    return checkNotNull(iterator);
159  }
160
161  /**
162   * Returns the number of elements remaining in {@code iterator}. The iterator
163   * will be left exhausted: its {@code hasNext()} method will return
164   * {@code false}.
165   */
166  public static int size(Iterator<?> iterator) {
167    long count = 0L;
168    while (iterator.hasNext()) {
169      iterator.next();
170      count++;
171    }
172    return Ints.saturatedCast(count);
173  }
174
175  /**
176   * Returns {@code true} if {@code iterator} contains {@code element}.
177   */
178  public static boolean contains(Iterator<?> iterator, @Nullable Object element) {
179    if (element == null) {
180      while (iterator.hasNext()) {
181        if (iterator.next() == null) {
182          return true;
183        }
184      }
185    } else {
186      while (iterator.hasNext()) {
187        if (element.equals(iterator.next())) {
188          return true;
189        }
190      }
191    }
192    return false;
193  }
194
195  /**
196   * Traverses an iterator and removes every element that belongs to the
197   * provided collection. The iterator will be left exhausted: its
198   * {@code hasNext()} method will return {@code false}.
199   *
200   * @param removeFrom the iterator to (potentially) remove elements from
201   * @param elementsToRemove the elements to remove
202   * @return {@code true} if any element was removed from {@code iterator}
203   */
204  @CanIgnoreReturnValue
205  public static boolean removeAll(Iterator<?> removeFrom, Collection<?> elementsToRemove) {
206    checkNotNull(elementsToRemove);
207    boolean result = false;
208    while (removeFrom.hasNext()) {
209      if (elementsToRemove.contains(removeFrom.next())) {
210        removeFrom.remove();
211        result = true;
212      }
213    }
214    return result;
215  }
216
217  /**
218   * Removes every element that satisfies the provided predicate from the
219   * iterator. The iterator will be left exhausted: its {@code hasNext()}
220   * method will return {@code false}.
221   *
222   * @param removeFrom the iterator to (potentially) remove elements from
223   * @param predicate a predicate that determines whether an element should
224   *     be removed
225   * @return {@code true} if any elements were removed from the iterator
226   * @since 2.0
227   */
228  @CanIgnoreReturnValue
229  public static <T> boolean removeIf(Iterator<T> removeFrom, Predicate<? super T> predicate) {
230    checkNotNull(predicate);
231    boolean modified = false;
232    while (removeFrom.hasNext()) {
233      if (predicate.apply(removeFrom.next())) {
234        removeFrom.remove();
235        modified = true;
236      }
237    }
238    return modified;
239  }
240
241  /**
242   * Traverses an iterator and removes every element that does not belong to the
243   * provided collection. The iterator will be left exhausted: its
244   * {@code hasNext()} method will return {@code false}.
245   *
246   * @param removeFrom the iterator to (potentially) remove elements from
247   * @param elementsToRetain the elements to retain
248   * @return {@code true} if any element was removed from {@code iterator}
249   */
250  @CanIgnoreReturnValue
251  public static boolean retainAll(Iterator<?> removeFrom, Collection<?> elementsToRetain) {
252    checkNotNull(elementsToRetain);
253    boolean result = false;
254    while (removeFrom.hasNext()) {
255      if (!elementsToRetain.contains(removeFrom.next())) {
256        removeFrom.remove();
257        result = true;
258      }
259    }
260    return result;
261  }
262
263  /**
264   * Determines whether two iterators contain equal elements in the same order.
265   * More specifically, this method returns {@code true} if {@code iterator1}
266   * and {@code iterator2} contain the same number of elements and every element
267   * of {@code iterator1} is equal to the corresponding element of
268   * {@code iterator2}.
269   *
270   * <p>Note that this will modify the supplied iterators, since they will have
271   * been advanced some number of elements forward.
272   */
273  public static boolean elementsEqual(Iterator<?> iterator1, Iterator<?> iterator2) {
274    while (iterator1.hasNext()) {
275      if (!iterator2.hasNext()) {
276        return false;
277      }
278      Object o1 = iterator1.next();
279      Object o2 = iterator2.next();
280      if (!Objects.equal(o1, o2)) {
281        return false;
282      }
283    }
284    return !iterator2.hasNext();
285  }
286
287  /**
288   * Returns a string representation of {@code iterator}, with the format
289   * {@code [e1, e2, ..., en]}. The iterator will be left exhausted: its
290   * {@code hasNext()} method will return {@code false}.
291   */
292  public static String toString(Iterator<?> iterator) {
293    StringBuilder sb = new StringBuilder().append('[');
294    boolean first = true;
295    while (iterator.hasNext()) {
296      if (!first) {
297        sb.append(", ");
298      }
299      first = false;
300      sb.append(iterator.next());
301    }
302    return sb.append(']').toString();
303  }
304
305  /**
306   * Returns the single element contained in {@code iterator}.
307   *
308   * @throws NoSuchElementException if the iterator is empty
309   * @throws IllegalArgumentException if the iterator contains multiple
310   *     elements.  The state of the iterator is unspecified.
311   */
312  @CanIgnoreReturnValue // TODO(kak): Consider removing this?
313  public static <T> T getOnlyElement(Iterator<T> iterator) {
314    T first = iterator.next();
315    if (!iterator.hasNext()) {
316      return first;
317    }
318
319    StringBuilder sb = new StringBuilder().append("expected one element but was: <").append(first);
320    for (int i = 0; i < 4 && iterator.hasNext(); i++) {
321      sb.append(", ").append(iterator.next());
322    }
323    if (iterator.hasNext()) {
324      sb.append(", ...");
325    }
326    sb.append('>');
327
328    throw new IllegalArgumentException(sb.toString());
329  }
330
331  /**
332   * Returns the single element contained in {@code iterator}, or {@code
333   * defaultValue} if the iterator is empty.
334   *
335   * @throws IllegalArgumentException if the iterator contains multiple
336   *     elements.  The state of the iterator is unspecified.
337   */
338  @CanIgnoreReturnValue // TODO(kak): Consider removing this?
339  @Nullable
340  public static <T> T getOnlyElement(Iterator<? extends T> iterator, @Nullable T defaultValue) {
341    return iterator.hasNext() ? getOnlyElement(iterator) : defaultValue;
342  }
343
344  /**
345   * Copies an iterator's elements into an array. The iterator will be left
346   * exhausted: its {@code hasNext()} method will return {@code false}.
347   *
348   * @param iterator the iterator to copy
349   * @param type the type of the elements
350   * @return a newly-allocated array into which all the elements of the iterator
351   *         have been copied
352   */
353  @GwtIncompatible // Array.newInstance(Class, int)
354  public static <T> T[] toArray(Iterator<? extends T> iterator, Class<T> type) {
355    List<T> list = Lists.newArrayList(iterator);
356    return Iterables.toArray(list, type);
357  }
358
359  /**
360   * Adds all elements in {@code iterator} to {@code collection}. The iterator
361   * will be left exhausted: its {@code hasNext()} method will return
362   * {@code false}.
363   *
364   * @return {@code true} if {@code collection} was modified as a result of this
365   *         operation
366   */
367  @CanIgnoreReturnValue
368  public static <T> boolean addAll(Collection<T> addTo, Iterator<? extends T> iterator) {
369    checkNotNull(addTo);
370    checkNotNull(iterator);
371    boolean wasModified = false;
372    while (iterator.hasNext()) {
373      wasModified |= addTo.add(iterator.next());
374    }
375    return wasModified;
376  }
377
378  /**
379   * Returns the number of elements in the specified iterator that equal the
380   * specified object. The iterator will be left exhausted: its
381   * {@code hasNext()} method will return {@code false}.
382   *
383   * @see Collections#frequency
384   */
385  public static int frequency(Iterator<?> iterator, @Nullable Object element) {
386    int count = 0;
387    while (contains(iterator, element)) {
388      // Since it lives in the same class, we know contains gets to the element and then stops,
389      // though that isn't currently publicly documented.
390      count++;
391    }
392    return count;
393  }
394
395  /**
396   * Returns an iterator that cycles indefinitely over the elements of {@code
397   * iterable}.
398   *
399   * <p>The returned iterator supports {@code remove()} if the provided iterator
400   * does. After {@code remove()} is called, subsequent cycles omit the removed
401   * element, which is no longer in {@code iterable}. The iterator's
402   * {@code hasNext()} method returns {@code true} until {@code iterable} is
403   * empty.
404   *
405   * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an
406   * infinite loop. You should use an explicit {@code break} or be certain that
407   * you will eventually remove all the elements.
408   */
409  public static <T> Iterator<T> cycle(final Iterable<T> iterable) {
410    checkNotNull(iterable);
411    return new Iterator<T>() {
412      Iterator<T> iterator = emptyModifiableIterator();
413
414      @Override
415      public boolean hasNext() {
416        /*
417         * Don't store a new Iterator until we know the user can't remove() the last returned
418         * element anymore. Otherwise, when we remove from the old iterator, we may be invalidating
419         * the new one. The result is a ConcurrentModificationException or other bad behavior.
420         *
421         * (If we decide that we really, really hate allocating two Iterators per cycle instead of
422         * one, we can optimistically store the new Iterator and then be willing to throw it out if
423         * the user calls remove().)
424         */
425        return iterator.hasNext() || iterable.iterator().hasNext();
426      }
427
428      @Override
429      public T next() {
430        if (!iterator.hasNext()) {
431          iterator = iterable.iterator();
432          if (!iterator.hasNext()) {
433            throw new NoSuchElementException();
434          }
435        }
436        return iterator.next();
437      }
438
439      @Override
440      public void remove() {
441        iterator.remove();
442      }
443    };
444  }
445
446  /**
447   * Returns an iterator that cycles indefinitely over the provided elements.
448   *
449   * <p>The returned iterator supports {@code remove()}. After {@code remove()}
450   * is called, subsequent cycles omit the removed
451   * element, but {@code elements} does not change. The iterator's
452   * {@code hasNext()} method returns {@code true} until all of the original
453   * elements have been removed.
454   *
455   * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an
456   * infinite loop. You should use an explicit {@code break} or be certain that
457   * you will eventually remove all the elements.
458   */
459  @SafeVarargs
460  public static <T> Iterator<T> cycle(T... elements) {
461    return cycle(Lists.newArrayList(elements));
462  }
463
464  /**
465   * Returns an Iterator that walks the specified array, nulling out elements behind it.
466   * This can avoid memory leaks when an element is no longer necessary.
467   *
468   * This is mainly just to avoid the intermediate ArrayDeque in ConsumingQueueIterator.
469   */
470  private static <T> Iterator<T> consumingForArray(final T... elements) {
471    return new UnmodifiableIterator<T>() {
472      int index = 0;
473
474      @Override
475      public boolean hasNext() {
476        return index < elements.length;
477      }
478
479      @Override
480      public T next() {
481        if (!hasNext()) {
482          throw new NoSuchElementException();
483        }
484        T result = elements[index];
485        elements[index] = null;
486        index++;
487        return result;
488      }
489    };
490  }
491
492  /**
493   * Combines two iterators into a single iterator. The returned iterator
494   * iterates across the elements in {@code a}, followed by the elements in
495   * {@code b}. The source iterators are not polled until necessary.
496   *
497   * <p>The returned iterator supports {@code remove()} when the corresponding
498   * input iterator supports it.
499   */
500  public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b) {
501    checkNotNull(a);
502    checkNotNull(b);
503    return concat(consumingForArray(a, b));
504  }
505
506  /**
507   * Combines three iterators into a single iterator. The returned iterator
508   * iterates across the elements in {@code a}, followed by the elements in
509   * {@code b}, followed by the elements in {@code c}. The source iterators
510   * are not polled until necessary.
511   *
512   * <p>The returned iterator supports {@code remove()} when the corresponding
513   * input iterator supports it.
514   */
515  public static <T> Iterator<T> concat(
516      Iterator<? extends T> a, Iterator<? extends T> b, Iterator<? extends T> c) {
517    checkNotNull(a);
518    checkNotNull(b);
519    checkNotNull(c);
520    return concat(consumingForArray(a, b, c));
521  }
522
523  /**
524   * Combines four iterators into a single iterator. The returned iterator
525   * iterates across the elements in {@code a}, followed by the elements in
526   * {@code b}, followed by the elements in {@code c}, followed by the elements
527   * in {@code d}. The source iterators are not polled until necessary.
528   *
529   * <p>The returned iterator supports {@code remove()} when the corresponding
530   * input iterator supports it.
531   */
532  public static <T> Iterator<T> concat(
533      Iterator<? extends T> a,
534      Iterator<? extends T> b,
535      Iterator<? extends T> c,
536      Iterator<? extends T> d) {
537    checkNotNull(a);
538    checkNotNull(b);
539    checkNotNull(c);
540    checkNotNull(d);
541    return concat(consumingForArray(a, b, c, d));
542  }
543
544  /**
545   * Combines multiple iterators into a single iterator. The returned iterator
546   * iterates across the elements of each iterator in {@code inputs}. The input
547   * iterators are not polled until necessary.
548   *
549   * <p>The returned iterator supports {@code remove()} when the corresponding
550   * input iterator supports it.
551   *
552   * @throws NullPointerException if any of the provided iterators is null
553   */
554  public static <T> Iterator<T> concat(Iterator<? extends T>... inputs) {
555    return concatNoDefensiveCopy(Arrays.copyOf(inputs, inputs.length));
556  }
557
558  /**
559   * Concats a varargs array of iterators without making a defensive copy of the array.
560   */
561  static <T> Iterator<T> concatNoDefensiveCopy(Iterator<? extends T>... inputs) {
562    for (Iterator<? extends T> input : checkNotNull(inputs)) {
563      checkNotNull(input);
564    }
565    return concat(consumingForArray(inputs));
566  }
567
568  /**
569   * Combines multiple iterators into a single iterator. The returned iterator
570   * iterates across the elements of each iterator in {@code inputs}. The input
571   * iterators are not polled until necessary.
572   *
573   * <p>The returned iterator supports {@code remove()} when the corresponding
574   * input iterator supports it. The methods of the returned iterator may throw
575   * {@code NullPointerException} if any of the input iterators is null.
576   */
577  public static <T> Iterator<T> concat(Iterator<? extends Iterator<? extends T>> inputs) {
578    return new ConcatenatedIterator<T>(inputs);
579  }
580
581  /**
582   * Divides an iterator into unmodifiable sublists of the given size (the final
583   * list may be smaller). For example, partitioning an iterator containing
584   * {@code [a, b, c, d, e]} with a partition size of 3 yields {@code
585   * [[a, b, c], [d, e]]} -- an outer iterator containing two inner lists of
586   * three and two elements, all in the original order.
587   *
588   * <p>The returned lists implement {@link java.util.RandomAccess}.
589   *
590   * @param iterator the iterator to return a partitioned view of
591   * @param size the desired size of each partition (the last may be smaller)
592   * @return an iterator of immutable lists containing the elements of {@code
593   *     iterator} divided into partitions
594   * @throws IllegalArgumentException if {@code size} is nonpositive
595   */
596  public static <T> UnmodifiableIterator<List<T>> partition(Iterator<T> iterator, int size) {
597    return partitionImpl(iterator, size, false);
598  }
599
600  /**
601   * Divides an iterator into unmodifiable sublists of the given size, padding
602   * the final iterator with null values if necessary. For example, partitioning
603   * an iterator containing {@code [a, b, c, d, e]} with a partition size of 3
604   * yields {@code [[a, b, c], [d, e, null]]} -- an outer iterator containing
605   * two inner lists of three elements each, all in the original order.
606   *
607   * <p>The returned lists implement {@link java.util.RandomAccess}.
608   *
609   * @param iterator the iterator to return a partitioned view of
610   * @param size the desired size of each partition
611   * @return an iterator of immutable lists containing the elements of {@code
612   *     iterator} divided into partitions (the final iterable may have
613   *     trailing null elements)
614   * @throws IllegalArgumentException if {@code size} is nonpositive
615   */
616  public static <T> UnmodifiableIterator<List<T>> paddedPartition(Iterator<T> iterator, int size) {
617    return partitionImpl(iterator, size, true);
618  }
619
620  private static <T> UnmodifiableIterator<List<T>> partitionImpl(
621      final Iterator<T> iterator, final int size, final boolean pad) {
622    checkNotNull(iterator);
623    checkArgument(size > 0);
624    return new UnmodifiableIterator<List<T>>() {
625      @Override
626      public boolean hasNext() {
627        return iterator.hasNext();
628      }
629
630      @Override
631      public List<T> next() {
632        if (!hasNext()) {
633          throw new NoSuchElementException();
634        }
635        Object[] array = new Object[size];
636        int count = 0;
637        for (; count < size && iterator.hasNext(); count++) {
638          array[count] = iterator.next();
639        }
640        for (int i = count; i < size; i++) {
641          array[i] = null; // for GWT
642        }
643
644        @SuppressWarnings("unchecked") // we only put Ts in it
645        List<T> list = Collections.unmodifiableList((List<T>) Arrays.asList(array));
646        return (pad || count == size) ? list : list.subList(0, count);
647      }
648    };
649  }
650
651  /**
652   * Returns a view of {@code unfiltered} containing all elements that satisfy
653   * the input predicate {@code retainIfTrue}.
654   */
655  public static <T> UnmodifiableIterator<T> filter(
656      final Iterator<T> unfiltered, final Predicate<? super T> retainIfTrue) {
657    checkNotNull(unfiltered);
658    checkNotNull(retainIfTrue);
659    return new AbstractIterator<T>() {
660      @Override
661      protected T computeNext() {
662        while (unfiltered.hasNext()) {
663          T element = unfiltered.next();
664          if (retainIfTrue.apply(element)) {
665            return element;
666          }
667        }
668        return endOfData();
669      }
670    };
671  }
672
673  /**
674   * Returns a view of {@code unfiltered} containing all elements that are of
675   * the type {@code desiredType}.
676   */
677  @SuppressWarnings("unchecked") // can cast to <T> because non-Ts are removed
678  @GwtIncompatible // Class.isInstance
679  public static <T> UnmodifiableIterator<T> filter(Iterator<?> unfiltered, Class<T> desiredType) {
680    return (UnmodifiableIterator<T>) filter(unfiltered, instanceOf(desiredType));
681  }
682
683  /**
684   * Returns {@code true} if one or more elements returned by {@code iterator}
685   * satisfy the given predicate.
686   */
687  public static <T> boolean any(Iterator<T> iterator, Predicate<? super T> predicate) {
688    return indexOf(iterator, predicate) != -1;
689  }
690
691  /**
692   * Returns {@code true} if every element returned by {@code iterator}
693   * satisfies the given predicate. If {@code iterator} is empty, {@code true}
694   * is returned.
695   */
696  public static <T> boolean all(Iterator<T> iterator, Predicate<? super T> predicate) {
697    checkNotNull(predicate);
698    while (iterator.hasNext()) {
699      T element = iterator.next();
700      if (!predicate.apply(element)) {
701        return false;
702      }
703    }
704    return true;
705  }
706
707  /**
708   * Returns the first element in {@code iterator} that satisfies the given
709   * predicate; use this method only when such an element is known to exist. If
710   * no such element is found, the iterator will be left exhausted: its {@code
711   * hasNext()} method will return {@code false}. If it is possible that
712   * <i>no</i> element will match, use {@link #tryFind} or {@link
713   * #find(Iterator, Predicate, Object)} instead.
714   *
715   * @throws NoSuchElementException if no element in {@code iterator} matches
716   *     the given predicate
717   */
718  public static <T> T find(Iterator<T> iterator, Predicate<? super T> predicate) {
719    checkNotNull(iterator);
720    checkNotNull(predicate);
721    while (iterator.hasNext()) {
722      T t = iterator.next();
723      if (predicate.apply(t)) {
724        return t;
725      }
726    }
727    throw new NoSuchElementException();
728  }
729
730  /**
731   * Returns the first element in {@code iterator} that satisfies the given
732   * predicate. If no such element is found, {@code defaultValue} will be
733   * returned from this method and the iterator will be left exhausted: its
734   * {@code hasNext()} method will return {@code false}. Note that this can
735   * usually be handled more naturally using {@code
736   * tryFind(iterator, predicate).or(defaultValue)}.
737   *
738   * @since 7.0
739   */
740  @Nullable
741  public static <T> T find(
742      Iterator<? extends T> iterator, Predicate<? super T> predicate, @Nullable T defaultValue) {
743    checkNotNull(iterator);
744    checkNotNull(predicate);
745    while (iterator.hasNext()) {
746      T t = iterator.next();
747      if (predicate.apply(t)) {
748        return t;
749      }
750    }
751    return defaultValue;
752  }
753
754  /**
755   * Returns an {@link Optional} containing the first element in {@code
756   * iterator} that satisfies the given predicate, if such an element exists. If
757   * no such element is found, an empty {@link Optional} will be returned from
758   * this method and the iterator will be left exhausted: its {@code
759   * hasNext()} method will return {@code false}.
760   *
761   * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code
762   * null}. If {@code null} is matched in {@code iterator}, a
763   * NullPointerException will be thrown.
764   *
765   * @since 11.0
766   */
767  public static <T> Optional<T> tryFind(Iterator<T> iterator, Predicate<? super T> predicate) {
768    checkNotNull(iterator);
769    checkNotNull(predicate);
770    while (iterator.hasNext()) {
771      T t = iterator.next();
772      if (predicate.apply(t)) {
773        return Optional.of(t);
774      }
775    }
776    return Optional.absent();
777  }
778
779  /**
780   * Returns the index in {@code iterator} of the first element that satisfies
781   * the provided {@code predicate}, or {@code -1} if the Iterator has no such
782   * elements.
783   *
784   * <p>More formally, returns the lowest index {@code i} such that
785   * {@code predicate.apply(Iterators.get(iterator, i))} returns {@code true},
786   * or {@code -1} if there is no such index.
787   *
788   * <p>If -1 is returned, the iterator will be left exhausted: its
789   * {@code hasNext()} method will return {@code false}.  Otherwise,
790   * the iterator will be set to the element which satisfies the
791   * {@code predicate}.
792   *
793   * @since 2.0
794   */
795  public static <T> int indexOf(Iterator<T> iterator, Predicate<? super T> predicate) {
796    checkNotNull(predicate, "predicate");
797    for (int i = 0; iterator.hasNext(); i++) {
798      T current = iterator.next();
799      if (predicate.apply(current)) {
800        return i;
801      }
802    }
803    return -1;
804  }
805
806  /**
807   * Returns a view containing the result of applying {@code function} to each
808   * element of {@code fromIterator}.
809   *
810   * <p>The returned iterator supports {@code remove()} if {@code fromIterator}
811   * does. After a successful {@code remove()} call, {@code fromIterator} no
812   * longer contains the corresponding element.
813   */
814  public static <F, T> Iterator<T> transform(
815      final Iterator<F> fromIterator, final Function<? super F, ? extends T> function) {
816    checkNotNull(function);
817    return new TransformedIterator<F, T>(fromIterator) {
818      @Override
819      T transform(F from) {
820        return function.apply(from);
821      }
822    };
823  }
824
825  /**
826   * Advances {@code iterator} {@code position + 1} times, returning the
827   * element at the {@code position}th position.
828   *
829   * @param position position of the element to return
830   * @return the element at the specified position in {@code iterator}
831   * @throws IndexOutOfBoundsException if {@code position} is negative or
832   *     greater than or equal to the number of elements remaining in
833   *     {@code iterator}
834   */
835  public static <T> T get(Iterator<T> iterator, int position) {
836    checkNonnegative(position);
837    int skipped = advance(iterator, position);
838    if (!iterator.hasNext()) {
839      throw new IndexOutOfBoundsException(
840          "position ("
841              + position
842              + ") must be less than the number of elements that remained ("
843              + skipped
844              + ")");
845    }
846    return iterator.next();
847  }
848
849  static void checkNonnegative(int position) {
850    if (position < 0) {
851      throw new IndexOutOfBoundsException("position (" + position + ") must not be negative");
852    }
853  }
854
855  /**
856   * Advances {@code iterator} {@code position + 1} times, returning the
857   * element at the {@code position}th position or {@code defaultValue}
858   * otherwise.
859   *
860   * @param position position of the element to return
861   * @param defaultValue the default value to return if the iterator is empty
862   *     or if {@code position} is greater than the number of elements
863   *     remaining in {@code iterator}
864   * @return the element at the specified position in {@code iterator} or
865   *     {@code defaultValue} if {@code iterator} produces fewer than
866   *     {@code position + 1} elements.
867   * @throws IndexOutOfBoundsException if {@code position} is negative
868   * @since 4.0
869   */
870  @Nullable
871  public static <T> T get(Iterator<? extends T> iterator, int position, @Nullable T defaultValue) {
872    checkNonnegative(position);
873    advance(iterator, position);
874    return getNext(iterator, defaultValue);
875  }
876
877  /**
878   * Returns the next element in {@code iterator} or {@code defaultValue} if
879   * the iterator is empty.  The {@link Iterables} analog to this method is
880   * {@link Iterables#getFirst}.
881   *
882   * @param defaultValue the default value to return if the iterator is empty
883   * @return the next element of {@code iterator} or the default value
884   * @since 7.0
885   */
886  @Nullable
887  public static <T> T getNext(Iterator<? extends T> iterator, @Nullable T defaultValue) {
888    return iterator.hasNext() ? iterator.next() : defaultValue;
889  }
890
891  /**
892   * Advances {@code iterator} to the end, returning the last element.
893   *
894   * @return the last element of {@code iterator}
895   * @throws NoSuchElementException if the iterator is empty
896   */
897  public static <T> T getLast(Iterator<T> iterator) {
898    while (true) {
899      T current = iterator.next();
900      if (!iterator.hasNext()) {
901        return current;
902      }
903    }
904  }
905
906  /**
907   * Advances {@code iterator} to the end, returning the last element or
908   * {@code defaultValue} if the iterator is empty.
909   *
910   * @param defaultValue the default value to return if the iterator is empty
911   * @return the last element of {@code iterator}
912   * @since 3.0
913   */
914  @Nullable
915  public static <T> T getLast(Iterator<? extends T> iterator, @Nullable T defaultValue) {
916    return iterator.hasNext() ? getLast(iterator) : defaultValue;
917  }
918
919  /**
920   * Calls {@code next()} on {@code iterator}, either {@code numberToAdvance} times
921   * or until {@code hasNext()} returns {@code false}, whichever comes first.
922   *
923   * @return the number of elements the iterator was advanced
924   * @since 13.0 (since 3.0 as {@code Iterators.skip})
925   */
926  @CanIgnoreReturnValue
927  public static int advance(Iterator<?> iterator, int numberToAdvance) {
928    checkNotNull(iterator);
929    checkArgument(numberToAdvance >= 0, "numberToAdvance must be nonnegative");
930
931    int i;
932    for (i = 0; i < numberToAdvance && iterator.hasNext(); i++) {
933      iterator.next();
934    }
935    return i;
936  }
937
938  /**
939   * Returns a view containing the first {@code limitSize} elements of {@code
940   * iterator}. If {@code iterator} contains fewer than {@code limitSize}
941   * elements, the returned view contains all of its elements. The returned
942   * iterator supports {@code remove()} if {@code iterator} does.
943   *
944   * @param iterator the iterator to limit
945   * @param limitSize the maximum number of elements in the returned iterator
946   * @throws IllegalArgumentException if {@code limitSize} is negative
947   * @since 3.0
948   */
949  public static <T> Iterator<T> limit(final Iterator<T> iterator, final int limitSize) {
950    checkNotNull(iterator);
951    checkArgument(limitSize >= 0, "limit is negative");
952    return new Iterator<T>() {
953      private int count;
954
955      @Override
956      public boolean hasNext() {
957        return count < limitSize && iterator.hasNext();
958      }
959
960      @Override
961      public T next() {
962        if (!hasNext()) {
963          throw new NoSuchElementException();
964        }
965        count++;
966        return iterator.next();
967      }
968
969      @Override
970      public void remove() {
971        iterator.remove();
972      }
973    };
974  }
975
976  /**
977   * Returns a view of the supplied {@code iterator} that removes each element
978   * from the supplied {@code iterator} as it is returned.
979   *
980   * <p>The provided iterator must support {@link Iterator#remove()} or
981   * else the returned iterator will fail on the first call to {@code
982   * next}.
983   *
984   * @param iterator the iterator to remove and return elements from
985   * @return an iterator that removes and returns elements from the
986   *     supplied iterator
987   * @since 2.0
988   */
989  public static <T> Iterator<T> consumingIterator(final Iterator<T> iterator) {
990    checkNotNull(iterator);
991    return new UnmodifiableIterator<T>() {
992      @Override
993      public boolean hasNext() {
994        return iterator.hasNext();
995      }
996
997      @Override
998      public T next() {
999        T next = iterator.next();
1000        iterator.remove();
1001        return next;
1002      }
1003
1004      @Override
1005      public String toString() {
1006        return "Iterators.consumingIterator(...)";
1007      }
1008    };
1009  }
1010
1011  /**
1012   * Deletes and returns the next value from the iterator, or returns
1013   * {@code null} if there is no such value.
1014   */
1015  @Nullable
1016  static <T> T pollNext(Iterator<T> iterator) {
1017    if (iterator.hasNext()) {
1018      T result = iterator.next();
1019      iterator.remove();
1020      return result;
1021    } else {
1022      return null;
1023    }
1024  }
1025
1026  // Methods only in Iterators, not in Iterables
1027
1028  /**
1029   * Clears the iterator using its remove method.
1030   */
1031  static void clear(Iterator<?> iterator) {
1032    checkNotNull(iterator);
1033    while (iterator.hasNext()) {
1034      iterator.next();
1035      iterator.remove();
1036    }
1037  }
1038
1039  /**
1040   * Returns an iterator containing the elements of {@code array} in order. The
1041   * returned iterator is a view of the array; subsequent changes to the array
1042   * will be reflected in the iterator.
1043   *
1044   * <p><b>Note:</b> It is often preferable to represent your data using a
1045   * collection type, for example using {@link Arrays#asList(Object[])}, making
1046   * this method unnecessary.
1047   *
1048   * <p>The {@code Iterable} equivalent of this method is either {@link
1049   * Arrays#asList(Object[])}, {@link ImmutableList#copyOf(Object[])}},
1050   * or {@link ImmutableList#of}.
1051   */
1052  @SafeVarargs
1053  public static <T> UnmodifiableIterator<T> forArray(final T... array) {
1054    return forArray(array, 0, array.length, 0);
1055  }
1056
1057  private static final class ArrayItr<T> extends AbstractIndexedListIterator<T> {
1058    static final UnmodifiableListIterator<Object> EMPTY = new ArrayItr<Object>(
1059        new Object[0], 0, 0, 0);
1060
1061    private final T[] array;
1062    private final int offset;
1063
1064    ArrayItr(T[] array, int offset, int length, int index) {
1065      super(length, index);
1066      this.array = array;
1067      this.offset = offset;
1068    }
1069
1070    @Override
1071    protected T get(int index) {
1072      return array[offset + index];
1073    }
1074  }
1075
1076  /**
1077   * Returns a list iterator containing the elements in the specified range of
1078   * {@code array} in order, starting at the specified index.
1079   *
1080   * <p>The {@code Iterable} equivalent of this method is {@code
1081   * Arrays.asList(array).subList(offset, offset + length).listIterator(index)}.
1082   */
1083  static <T> UnmodifiableListIterator<T> forArray(
1084      final T[] array, final int offset, int length, int index) {
1085    checkArgument(length >= 0);
1086    int end = offset + length;
1087
1088    // Technically we should give a slightly more descriptive error on overflow
1089    Preconditions.checkPositionIndexes(offset, end, array.length);
1090    Preconditions.checkPositionIndex(index, length);
1091    if (length == 0) {
1092      return emptyListIterator();
1093    }
1094    return new ArrayItr<T>(array, offset, length, index);
1095  }
1096
1097  /**
1098   * Returns an iterator containing only {@code value}.
1099   *
1100   * <p>The {@link Iterable} equivalent of this method is {@link
1101   * Collections#singleton}.
1102   */
1103  public static <T> UnmodifiableIterator<T> singletonIterator(@Nullable final T value) {
1104    return new UnmodifiableIterator<T>() {
1105      boolean done;
1106
1107      @Override
1108      public boolean hasNext() {
1109        return !done;
1110      }
1111
1112      @Override
1113      public T next() {
1114        if (done) {
1115          throw new NoSuchElementException();
1116        }
1117        done = true;
1118        return value;
1119      }
1120    };
1121  }
1122
1123  /**
1124   * Adapts an {@code Enumeration} to the {@code Iterator} interface.
1125   *
1126   * <p>This method has no equivalent in {@link Iterables} because viewing an
1127   * {@code Enumeration} as an {@code Iterable} is impossible. However, the
1128   * contents can be <i>copied</i> into a collection using {@link
1129   * Collections#list}.
1130   */
1131  public static <T> UnmodifiableIterator<T> forEnumeration(final Enumeration<T> enumeration) {
1132    checkNotNull(enumeration);
1133    return new UnmodifiableIterator<T>() {
1134      @Override
1135      public boolean hasNext() {
1136        return enumeration.hasMoreElements();
1137      }
1138
1139      @Override
1140      public T next() {
1141        return enumeration.nextElement();
1142      }
1143    };
1144  }
1145
1146  /**
1147   * Adapts an {@code Iterator} to the {@code Enumeration} interface.
1148   *
1149   * <p>The {@code Iterable} equivalent of this method is either {@link
1150   * Collections#enumeration} (if you have a {@link Collection}), or
1151   * {@code Iterators.asEnumeration(collection.iterator())}.
1152   */
1153  public static <T> Enumeration<T> asEnumeration(final Iterator<T> iterator) {
1154    checkNotNull(iterator);
1155    return new Enumeration<T>() {
1156      @Override
1157      public boolean hasMoreElements() {
1158        return iterator.hasNext();
1159      }
1160
1161      @Override
1162      public T nextElement() {
1163        return iterator.next();
1164      }
1165    };
1166  }
1167
1168  /**
1169   * Implementation of PeekingIterator that avoids peeking unless necessary.
1170   */
1171  private static class PeekingImpl<E> implements PeekingIterator<E> {
1172
1173    private final Iterator<? extends E> iterator;
1174    private boolean hasPeeked;
1175    private E peekedElement;
1176
1177    public PeekingImpl(Iterator<? extends E> iterator) {
1178      this.iterator = checkNotNull(iterator);
1179    }
1180
1181    @Override
1182    public boolean hasNext() {
1183      return hasPeeked || iterator.hasNext();
1184    }
1185
1186    @Override
1187    public E next() {
1188      if (!hasPeeked) {
1189        return iterator.next();
1190      }
1191      E result = peekedElement;
1192      hasPeeked = false;
1193      peekedElement = null;
1194      return result;
1195    }
1196
1197    @Override
1198    public void remove() {
1199      checkState(!hasPeeked, "Can't remove after you've peeked at next");
1200      iterator.remove();
1201    }
1202
1203    @Override
1204    public E peek() {
1205      if (!hasPeeked) {
1206        peekedElement = iterator.next();
1207        hasPeeked = true;
1208      }
1209      return peekedElement;
1210    }
1211  }
1212
1213  /**
1214   * Returns a {@code PeekingIterator} backed by the given iterator.
1215   *
1216   * <p>Calls to the {@code peek} method with no intervening calls to {@code
1217   * next} do not affect the iteration, and hence return the same object each
1218   * time. A subsequent call to {@code next} is guaranteed to return the same
1219   * object again. For example: <pre>   {@code
1220   *
1221   *   PeekingIterator<String> peekingIterator =
1222   *       Iterators.peekingIterator(Iterators.forArray("a", "b"));
1223   *   String a1 = peekingIterator.peek(); // returns "a"
1224   *   String a2 = peekingIterator.peek(); // also returns "a"
1225   *   String a3 = peekingIterator.next(); // also returns "a"}</pre>
1226   *
1227   * <p>Any structural changes to the underlying iteration (aside from those
1228   * performed by the iterator's own {@link PeekingIterator#remove()} method)
1229   * will leave the iterator in an undefined state.
1230   *
1231   * <p>The returned iterator does not support removal after peeking, as
1232   * explained by {@link PeekingIterator#remove()}.
1233   *
1234   * <p>Note: If the given iterator is already a {@code PeekingIterator},
1235   * it <i>might</i> be returned to the caller, although this is neither
1236   * guaranteed to occur nor required to be consistent.  For example, this
1237   * method <i>might</i> choose to pass through recognized implementations of
1238   * {@code PeekingIterator} when the behavior of the implementation is
1239   * known to meet the contract guaranteed by this method.
1240   *
1241   * <p>There is no {@link Iterable} equivalent to this method, so use this
1242   * method to wrap each individual iterator as it is generated.
1243   *
1244   * @param iterator the backing iterator. The {@link PeekingIterator} assumes
1245   *     ownership of this iterator, so users should cease making direct calls
1246   *     to it after calling this method.
1247   * @return a peeking iterator backed by that iterator. Apart from the
1248   *     additional {@link PeekingIterator#peek()} method, this iterator behaves
1249   *     exactly the same as {@code iterator}.
1250   */
1251  public static <T> PeekingIterator<T> peekingIterator(Iterator<? extends T> iterator) {
1252    if (iterator instanceof PeekingImpl) {
1253      // Safe to cast <? extends T> to <T> because PeekingImpl only uses T
1254      // covariantly (and cannot be subclassed to add non-covariant uses).
1255      @SuppressWarnings("unchecked")
1256      PeekingImpl<T> peeking = (PeekingImpl<T>) iterator;
1257      return peeking;
1258    }
1259    return new PeekingImpl<T>(iterator);
1260  }
1261
1262  /**
1263   * Simply returns its argument.
1264   *
1265   * @deprecated no need to use this
1266   * @since 10.0
1267   */
1268  @Deprecated
1269  public static <T> PeekingIterator<T> peekingIterator(PeekingIterator<T> iterator) {
1270    return checkNotNull(iterator);
1271  }
1272
1273  /**
1274   * Returns an iterator over the merged contents of all given
1275   * {@code iterators}, traversing every element of the input iterators.
1276   * Equivalent entries will not be de-duplicated.
1277   *
1278   * <p>Callers must ensure that the source {@code iterators} are in
1279   * non-descending order as this method does not sort its input.
1280   *
1281   * <p>For any equivalent elements across all {@code iterators}, it is
1282   * undefined which element is returned first.
1283   *
1284   * @since 11.0
1285   */
1286  @Beta
1287  public static <T> UnmodifiableIterator<T> mergeSorted(
1288      Iterable<? extends Iterator<? extends T>> iterators, Comparator<? super T> comparator) {
1289    checkNotNull(iterators, "iterators");
1290    checkNotNull(comparator, "comparator");
1291
1292    return new MergingIterator<T>(iterators, comparator);
1293  }
1294
1295  /**
1296   * An iterator that performs a lazy N-way merge, calculating the next value
1297   * each time the iterator is polled. This amortizes the sorting cost over the
1298   * iteration and requires less memory than sorting all elements at once.
1299   *
1300   * <p>Retrieving a single element takes approximately O(log(M)) time, where M
1301   * is the number of iterators. (Retrieving all elements takes approximately
1302   * O(N*log(M)) time, where N is the total number of elements.)
1303   */
1304  private static class MergingIterator<T> extends UnmodifiableIterator<T> {
1305    final Queue<PeekingIterator<T>> queue;
1306
1307    public MergingIterator(
1308        Iterable<? extends Iterator<? extends T>> iterators,
1309        final Comparator<? super T> itemComparator) {
1310      // A comparator that's used by the heap, allowing the heap
1311      // to be sorted based on the top of each iterator.
1312      Comparator<PeekingIterator<T>> heapComparator =
1313          new Comparator<PeekingIterator<T>>() {
1314            @Override
1315            public int compare(PeekingIterator<T> o1, PeekingIterator<T> o2) {
1316              return itemComparator.compare(o1.peek(), o2.peek());
1317            }
1318          };
1319
1320      queue = new PriorityQueue<PeekingIterator<T>>(2, heapComparator);
1321
1322      for (Iterator<? extends T> iterator : iterators) {
1323        if (iterator.hasNext()) {
1324          queue.add(Iterators.peekingIterator(iterator));
1325        }
1326      }
1327    }
1328
1329    @Override
1330    public boolean hasNext() {
1331      return !queue.isEmpty();
1332    }
1333
1334    @Override
1335    public T next() {
1336      PeekingIterator<T> nextIter = queue.remove();
1337      T next = nextIter.next();
1338      if (nextIter.hasNext()) {
1339        queue.add(nextIter);
1340      }
1341      return next;
1342    }
1343  }
1344
1345  private static class ConcatenatedIterator<T> implements Iterator<T> {
1346    /* The last iterator to return an element.  Calls to remove() go to this iterator. */
1347    private Iterator<? extends T> toRemove;
1348
1349    /* The iterator currently returning elements. */
1350    private Iterator<? extends T> iterator;
1351
1352    /*
1353     * We track the "meta iterators," the iterators-of-iterators, below.  Usually, topMetaIterator
1354     * is the only one in use, but if we encounter nested concatenations, we start a deque of
1355     * meta-iterators rather than letting the nesting get arbitrarily deep.  This keeps each
1356     * operation O(1).
1357     */
1358
1359    private Iterator<? extends Iterator<? extends T>> topMetaIterator;
1360
1361    // Only becomes nonnull if we encounter nested concatenations.
1362    @Nullable
1363    private Deque<Iterator<? extends Iterator<? extends T>>> metaIterators;
1364
1365    ConcatenatedIterator(Iterator<? extends Iterator<? extends T>> metaIterator) {
1366      iterator = emptyIterator();
1367      topMetaIterator = checkNotNull(metaIterator);
1368    }
1369
1370    // Returns a nonempty meta-iterator or, if all meta-iterators are empty, null.
1371    @Nullable
1372    private Iterator<? extends Iterator<? extends T>> getTopMetaIterator() {
1373      while (topMetaIterator == null || !topMetaIterator.hasNext()) {
1374        if (metaIterators != null && !metaIterators.isEmpty()) {
1375          topMetaIterator = metaIterators.removeFirst();
1376        } else {
1377          return null;
1378        }
1379      }
1380      return topMetaIterator;
1381    }
1382
1383    @Override
1384    public boolean hasNext() {
1385      while (!checkNotNull(iterator).hasNext()) {
1386        // this weird checkNotNull positioning appears required by our tests, which expect
1387        // both hasNext and next to throw NPE if an input iterator is null.
1388
1389        topMetaIterator = getTopMetaIterator();
1390        if (topMetaIterator == null) {
1391          return false;
1392        }
1393
1394        iterator = topMetaIterator.next();
1395
1396        if (iterator instanceof ConcatenatedIterator) {
1397          // Instead of taking linear time in the number of nested concatenations, unpack
1398          // them into the queue
1399          @SuppressWarnings("unchecked")
1400          ConcatenatedIterator<T> topConcat = (ConcatenatedIterator<T>) iterator;
1401          iterator = topConcat.iterator;
1402
1403          // topConcat.topMetaIterator, then topConcat.metaIterators, then this.topMetaIterator,
1404          // then this.metaIterators
1405
1406          if (this.metaIterators == null) {
1407            this.metaIterators = new ArrayDeque<>();
1408          }
1409          this.metaIterators.addFirst(this.topMetaIterator);
1410          if (topConcat.metaIterators != null) {
1411            while (!topConcat.metaIterators.isEmpty()) {
1412              this.metaIterators.addFirst(topConcat.metaIterators.removeLast());
1413            }
1414          }
1415          this.topMetaIterator = topConcat.topMetaIterator;
1416        }
1417      }
1418      return true;
1419    }
1420
1421    @Override
1422    public T next() {
1423      if (hasNext()) {
1424        toRemove = iterator;
1425        return iterator.next();
1426      } else {
1427        throw new NoSuchElementException();
1428      }
1429    }
1430
1431    @Override
1432    public void remove() {
1433      CollectPreconditions.checkRemove(toRemove != null);
1434      toRemove.remove();
1435      toRemove = null;
1436    }
1437  }
1438
1439  /**
1440   * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
1441   */
1442  static <T> ListIterator<T> cast(Iterator<T> iterator) {
1443    return (ListIterator<T>) iterator;
1444  }
1445}