a whole bunch of stuff
[ephemerata.git] / KezvhLib / src-lib / net / kezvh / collections / AbstractIterator.java
blobe3428ce6dcdcef2c6dcd86b0fa8adbbd5d097259
1 package net.kezvh.collections;
3 import java.util.Iterator;
4 import java.util.NoSuchElementException;
6 /**
7 * @author afflux
8 * @param <T> type to iterate over
9 */
10 public abstract class AbstractIterator<T> implements Iterator<T> {
11 private T nextObject;
12 private boolean firstTime = true;
13 private boolean noMoreElements = false;
15 /**
16 * @return the next object
17 * @throws NoSuchElementException if there are no more elements
19 protected abstract T findNext() throws NoSuchElementException;
21 private T tryFindNext() {
22 this.firstTime = false;
23 try {
24 return this.findNext();
25 } catch (final NoSuchElementException e) {
26 this.noMoreElements = true;
27 return null;
31 /**
32 * @see java.util.Iterator#hasNext()
33 * @return x
35 public final boolean hasNext() {
36 if (this.firstTime)
37 this.nextObject = this.tryFindNext();
38 return !this.noMoreElements;
41 /**
42 * @see java.util.Iterator#next()
43 * @return x
45 public final T next() {
46 if (this.firstTime)
47 this.nextObject = this.tryFindNext();
48 if (!this.hasNext())
49 throw new NoSuchElementException();
50 try {
51 return this.nextObject;
52 } finally {
53 this.nextObject = this.tryFindNext();
57 /**
58 * By default, throws UnsupportedOperationException. This can be overridden.
60 * @see java.util.Iterator#remove()
62 public void remove() {
63 throw new UnsupportedOperationException();