Last active
May 31, 2020 05:38
-
-
Save LouiS0616/4fefbbe89e913e22c01d3f2ee6cfe5df to your computer and use it in GitHub Desktop.
覗き見できるイテレータ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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