Created
December 23, 2011 12:42
-
-
Save komiya-atsushi/1514100 to your computer and use it in GitHub Desktop.
木構造を再帰呼び出しで処理したくない人向けの Iterable なインタフェース。Iterator インタフェースで tree retrieval (pre-order) できます。
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
package hoge; | |
import java.util.Iterator; | |
import java.util.List; | |
import java.util.NoSuchElementException; | |
import java.util.Stack; | |
public interface Retrievable<T extends Retrievable> extends Iterable<T> { | |
List<T> children(); | |
public static class PreOrderRetriever<T extends Retrievable> implements Iterator<T> { | |
private Stack<Iterator<T>> stack = new Stack<Iterator<T>>(); | |
private T nextObject; | |
public PreOrderRetriever(T source, boolean returnsSourceAtFirst) { | |
stack.push(source.children().iterator()); | |
if (returnsSourceAtFirst) { | |
nextObject = source; | |
} | |
} | |
@Override | |
public boolean hasNext() { | |
if (nextObject != null) { | |
return true; | |
} | |
Iterator<T> usingItr = null; | |
while (!stack.isEmpty()) { | |
Iterator<T> i = stack.pop(); | |
if (!i.hasNext()) { | |
continue; | |
} | |
usingItr = i; | |
break; | |
} | |
if (usingItr == null) { | |
return false; | |
} | |
nextObject = usingItr.next(); | |
stack.push(usingItr); | |
stack.push(nextObject.children().iterator()); | |
return true; | |
} | |
@Override | |
public T next() { | |
if (!hasNext()) { | |
throw new NoSuchElementException(); | |
} | |
T result = nextObject; | |
nextObject = null; | |
return result; | |
} | |
@Override | |
public void remove() { | |
throw new UnsupportedOperationException(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment