View Javadoc

1   package ca.uhn.hl7v2.testpanel.util;
2   
3   import java.util.Iterator;
4   
5   public class PushBackIterator<E> implements Iterator<E> {
6   	private E myPreviousValue = null;
7   	private E mySavedValue = null;
8   	private final Iterator<E> myWrappedIterator;
9   	
10  	/**
11  	 * Constructor
12  	 */
13  	public PushBackIterator(Iterator<E> theIteratorToWrap) {
14  		this.myWrappedIterator = theIteratorToWrap;
15  	}
16  
17  	/**
18  	 * {@inheritDoc}
19  	 */
20  	public boolean hasNext() {
21  		return mySavedValue != null || myWrappedIterator.hasNext();
22  	}
23  
24  
25  	/**
26  	 * {@inheritDoc}
27  	 */
28  	public E next() {
29  		if (mySavedValue != null) {
30  			try {
31  				return myPreviousValue = mySavedValue;
32  			} finally {
33  				mySavedValue = null;
34  			}
35  		}
36  		return myPreviousValue = myWrappedIterator.next();
37  	}
38  
39  
40  	public E previous() {
41  		return myPreviousValue;
42  	}
43  
44  
45  	public void pushBack() {
46  		mySavedValue = myPreviousValue;
47  	}
48  
49  
50  	/**
51  	 * {@inheritDoc}
52  	 */
53  	public void remove() {
54  		if (mySavedValue != null) {
55  			throw new IllegalStateException("Cannot remove when next element has been pushed back");
56  		}
57  		myWrappedIterator.remove();
58  	}
59  }