All Downloads are FREE. Search and download functionalities are using the official Maven repository.

it.twenfir.antlr.ast.ChildrenIterator Maven / Gradle / Ivy

There is a newer version: 0.1.3
Show newest version
package it.twenfir.antlr.ast;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * An iterator that only returns elements of the specified class.
 * 
 * @param  the type of the returned elements
 */
public class ChildrenIterator implements Iterator {

	Iterator iter;
	NodeT current;
	Class clazz;
	
	/**
	 * Constructor.
	 * 
	 * @param iter  an iterator from which to extract elements
	 * @param clazz the class object of the type elements must belong to
	 */
	public ChildrenIterator(Iterator iter, Class clazz) {
		this.iter = iter;
		this.clazz = clazz;
	}

	@SuppressWarnings("unchecked")
	private void advance() {
		while ( iter.hasNext() ) {
			if ( current != null ) {
				break;
			}
			AstNode n = iter.next();
			if ( clazz.isInstance(n) ) {
				current = (NodeT) n;
			}
		}
	}
	
	/** 
	 * Return whether the iterator has more elements.
	 * 
	 * @return true if there are elements available, false otherwise
	 */
	@Override
	public boolean hasNext() {
		advance();
		return current != null;
	}
	
	/** 
	 * Return the current element and advance to the next position.
	 * 
	 * @return the current element 
	 */
	@Override
	public NodeT next() {
		advance();
		if ( current == null ) {
			throw new NoSuchElementException();
		}
		NodeT value = current;
		current = null;
		return value;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy