View Javadoc

1   package cz.cuni.amis.utils.iterators;
2   
3   import java.util.Iterator;
4   
5   /**
6    * Implements a circular iterator that iterates over any reasonable iterable instance.
7    * Not fully tested!
8    * @author Radek 'Black_Hand' Pibil
9    *
10   * @param <E> contents of the iterable
11   */
12  public class CircularIterator<E> implements Iterator<E> {
13  	
14  	protected boolean passedEnd = false;
15  	private Iterable<E> toIterateOver;
16  	private Iterator<E> iterator;
17  	
18  	public CircularIterator(Iterable<E> toIterateOver) {
19  		this.toIterateOver = toIterateOver;
20  		iterator = toIterateOver.iterator();
21  	}
22  
23  	@Override
24  	public boolean hasNext() {
25  		return toIterateOver.iterator().hasNext();
26  	}
27  
28  	@Override
29  	public E next() {
30  		E value = iterator.next();
31  		if (!iterator.hasNext()) {
32  			restartIterator();
33  			passedEnd = true;
34  		}
35  		return value;
36  	}
37  
38  	@Override
39  	public void remove() {
40  		iterator.remove();
41  	}
42  	
43  	public boolean hasPassedEnd() {
44  		if (passedEnd) {
45  			passedEnd = false;
46  			return passedEnd;
47  		}
48  		return false;
49  	}
50  	
51  	protected Iterable<E> getIterable() {
52  		return toIterateOver;
53  	}
54  	
55  	protected Iterator<E> getIterator() {
56  		return iterator;
57  	}
58  	
59  	protected void restartIterator() {
60  		iterator = toIterateOver.iterator();	
61  	}
62  }