Returns an iterator that cycles indefinitely over the elements of iterable. The returned iterator supports remove() if the provided iterator does. After remove() is called, subsequent cycles omit the removed element, which is no longer in iterable. The iterator's
(final Iterable<T> iterable)
| 416 | |
| 417 | |
| 418 | public static <T> Iterator<T> cycle(final Iterable<T> iterable) { |
| 419 | checkNotNull(iterable); |
| 420 | return new Iterator<T>() { |
| 421 | Iterator<T> iterator = emptyModifiableIterator(); |
| 422 | |
| 423 | @Override |
| 424 | public boolean hasNext() { |
| 425 | /* |
| 426 | * Don't store a new Iterator until we know the user can't remove() the last returned |
| 427 | * element anymore. Otherwise, when we remove from the old iterator, we may be invalidating |
| 428 | * the new one. The result is a ConcurrentModificationException or other bad behavior. |
| 429 | * |
| 430 | * (If we decide that we really, really hate allocating two Iterators per cycle instead of |
| 431 | * one, we can optimistically store the new Iterator and then be willing to throw it out if |
| 432 | * the user calls remove().) |
| 433 | */ |
| 434 | return iterator.hasNext() || iterable.iterator().hasNext(); |
| 435 | } |
| 436 | |
| 437 | @Override |
| 438 | public T next() { |
| 439 | if (!iterator.hasNext()) { |
| 440 | iterator = iterable.iterator(); |
| 441 | if (!iterator.hasNext()) { |
| 442 | throw new NoSuchElementException(); |
| 443 | } |
| 444 | } |
| 445 | return iterator.next(); |
| 446 | } |
| 447 | |
| 448 | @Override |
| 449 | public void remove() { |
| 450 | iterator.remove(); |
| 451 | } |
| 452 | }; |
| 453 | } |
| 454 | |
| 455 | /** |
| 456 | * Returns an iterator that cycles indefinitely over the provided elements. |
no test coverage detected