Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make an iterator that never ends?

I was just wondering what the easiest way to iterate over a set indefinitely, i.e. when it reaches the end it next(); calls the first object. I'm assuming that this is not an already predefined function in Java, so just looking for the easiest way to implement this in Java.

like image 448
Bobby Avatar asked Jun 19 '09 06:06

Bobby


People also ask

Does iterator extend Iterable?

A class implementing the Iterable interface can be iterated over. Iterator is class that manages iteration over an Iterable. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.

What is a loop iterator?

An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical term for looping. To use an Iterator, you must import it from the java.util package.

How do you break an iterator loop?

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

Is iterator better than for loop?

Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.


2 Answers

How about ?

List<String> list = // ArraysList
Interator<String> it = null;

while(true) {
 it = list.iterator();
 while(it.hasNext()) {
   System.out.println(it.next());
 }
}
like image 132
bluelurker Avatar answered Sep 30 '22 04:09

bluelurker


If you don't want to use Guava but still want a reusable solution:

public static class CyclicIterator<E, C extends Collection<E>> implements Iterator<E> {
    final private C mElements;
    private Iterator<E> mIterator;

    public CyclicIterator(C elements) {
        mElements = elements;
        mIterator = elements.iterator();
    }

    @Override
    public boolean hasNext() {
        if (! mIterator.hasNext()) {
            mIterator = mElements.iterator();
        }
        return mIterator.hasNext();
    }

    @Override
    public E next() {
        if (! mIterator.hasNext()) {
            mIterator = mElements.iterator();
        }
        return mIterator.next();
    }
}

Note: this doesn't support the remove() method but it could easily be added if needed. Also it's not thread safe.

like image 34
Emanuel Moecklin Avatar answered Sep 30 '22 05:09

Emanuel Moecklin