Mercurial Hosting > nabble
view src/nabble/model/NodeIterator.java @ 62:4674ed7d56df default tip
remove n2
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Sat, 30 Sep 2023 20:25:29 -0600 |
parents | 7ecd1a4ef557 |
children |
line wrap: on
line source
package nabble.model; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.List; import java.util.ArrayList; import java.util.Collection; public abstract class NodeIterator<C extends Node> implements Iterator<C>, Iterable<C> { public abstract boolean hasNext(); public abstract C next() throws NoSuchElementException; public abstract void close(); public final void remove() { throw new UnsupportedOperationException(); } public final Iterator<C> iterator() { return this; } public void skip(int n) { while( hasNext() && n-- > 0 ) { next(); } } // calls close() public final boolean isEmpty() { try { return !hasNext(); } finally { close(); } } public final boolean contains(Node node) { try { while( hasNext() ) { if( next().equals(node) ) return true; } return false; } finally { close(); } } public final void addTo(Collection<Node> col) { while( hasNext() ) { col.add( next() ); } close(); } public List<Node> get(int i,int n) { List<Node> list = new ArrayList<Node>(); skip(i); while( hasNext() && n-- > 0 ) { list.add( next() ); } close(); return list; } public List<C> asList() { List<C> list = new ArrayList<C>(); while( hasNext()) { list.add( next() ); } return list; } public static final <T extends Node> NodeIterator<T> empty() { return new NodeIterator<T>() { @Override public boolean hasNext() { return false; } @Override public T next() throws NoSuchElementException { throw new NoSuchElementException(); } @Override public void close() {} }; } public static <T extends Node> NodeIterator<T> nodeIterator(final Iterator<T> iter) { return new NodeIterator<T>() { @Override public boolean hasNext() { return iter.hasNext(); } @Override public T next() throws NoSuchElementException { return iter.next(); } @Override public void close() {} }; } public static <T extends Node> NodeIterator<T> nodeIterator(final List<T> list) { return new NodeIterator<T>() { private Iterator<T> iter = null; private Iterator<T> iter() { if( iter == null ) iter = list.iterator(); return iter; } @Override public boolean hasNext() { return iter().hasNext(); } @Override public T next() throws NoSuchElementException { return iter().next(); } @Override public void close() {} @Override public List<T> asList() { return iter==null ? list : super.asList(); } }; } }