Skip to content

Instantly share code, notes, and snippets.

@LouiS0616
Last active May 31, 2020 05:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LouiS0616/4fefbbe89e913e22c01d3f2ee6cfe5df to your computer and use it in GitHub Desktop.
Save LouiS0616/4fefbbe89e913e22c01d3f2ee6cfe5df to your computer and use it in GitHub Desktop.
覗き見できるイテレータ
import java.util.Iterator;
import java.util.NoSuchElementException;
public class PeekableIterator<T> implements Iterator<T> {
//
private final Iterator<T> it;
private T nextElem;
private boolean hasNext = false;
public PeekableIterator(Iterable<T> iterable) {
this(iterable.iterator());
}
public PeekableIterator(Iterator<T> it) {
this.it = it;
if (it.hasNext()) {
nextElem = it.next();
hasNext = true;
}
}
//
public T peek() throws NoSuchElementException {
if (!hasNext()) {
throw new NoSuchElementException();
}
return nextElem;
}
//
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public T next() throws NoSuchElementException {
if (!hasNext()) {
throw new NoSuchElementException();
}
final T ret = nextElem;
if (it.hasNext()) {
nextElem = it.next();
} else {
hasNext = false;
}
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment