Iterator Pattern Example


import java.util.*; 
public class BitSetIterator implements Iterator<Boolean> { 
	private final BitSet bitset; 
	private int index;
 
	public BitSetIterator(BitSet bitset) { 
		this.bitset = bitset; 
	}
 
	public boolean hasNext() {   
		return index < bitset.length(); 
	} 
 
	public Boolean next() { 
		if (index >= bitset.length()) { 
			throw new NoSuchElementException(); 
		} 
		boolean b = bitset.get(index++); 
		return new Boolean(b); 
	} 
 
	public void remove() { 
		throw new UnsupportedOperationException(); 
	}
}

Two different usage examples:

public class TestClientBitSet { 
	public static void main(String[] args) { 
		// create BitSet and set some bits 
		BitSet bitset = new BitSet(); 
		bitset.set(1); 
		bitset.set(3400); 
		bitset.set(20); 
		bitset.set(47); 
		for (BitSetIterator iter = new BitSetIterator(bitset); iter.hasNext(); ) { 
			Boolean b = iter.next();               
			String tf = (b.booleanValue() ? "T" : "F"); 
			System.out.print(tf); 
		} 
		System.out.println(); 
	} 
} 
 
import java.util.*; 
public class TestClientIterator  {
	public static void main(String[] args) { 
		ArrayList<Object> al = new ArrayList<Object>(); 
		al.add(new Integer(42)); 
		al.add("test"); 
		al.add(new Double("-12.34")); 
		for (Iterator<Object> iter=al.iterator(); iter.hasNext(); ) 
			System.out.println( iter.next() ); 
		// Java 5 syntax (for-each loop)
		for (Object o:al) 
			System.out.println( o ); 
	} 
}
Comments