/*
 * ObserverDemo.java
 *
 * A simple example of the Iterator pattern.  We create a collection of strings
 * by using an array, and show how an Iterator object could be created for such
 * a collection.  We also create a second collection of strings by using a Set,
 * which of course can furnish an iterator.  We then show how the exact same 
 * code can be used to iterate over either collection, without knowing the
 * details of how the collection is actually implemented.
 *
 * For the purposes of this example, both collections are initialized to contain
 * a few constants.
 *
 * Of course, one does not normally create one's own iterators.  We do this here
 * to show what's "inside" one.
 *
 * Copyright (c) 2001 - Russell C. Bjork
 *
 */
 
import java.util.*;

// AN ARRAY OF STRINGS

class StringArray
{
	private String[] data = { "AARDVARK", "BUFFALO", "CAT", "DOG", "ELEPHANT" };
	
	public Iterator<String> iterator()
	{
		return new Iterator<String>() {
		
			private int position = 0;
			
			public boolean hasNext()
			{
				return position < data.length;
			}
			
			public String next()
			{
				String value = data[position];
				position ++;
				return value;
			}
			
			public void remove() throws UnsupportedOperationException
			{
				throw new UnsupportedOperationException("remove");
			}
		};
	}
}

// A SET OF STRINGS

class StringSet extends HashSet<String>
{
	public StringSet()
	{
		super();
		add("AARDVARK"); add("BUFFALO"); add("COW"); add("DOG"); add("ELEPHANT");
	}
}


// MAIN PROGRAM CLASS FOR DEMONSTRATION

class Demo
{
	public static void main(String [] args)
	{
		// Create two collections
		
		StringArray stringArray = new StringArray();
		StringSet stringSet = new StringSet();
		
		// Write out the contents of each, using an iterator obtained from it
		
		System.out.println("Contents of array collection");
		writeOut(stringArray.iterator());
		System.out.println("Contents of set collection");
		writeOut(stringSet.iterator());
	}

	/** Write out the contents of any collection, given an iterator for it
	 *
	 *	@param iterator the iterator for the collection
	 */
	public static void writeOut(Iterator iterator)
	{
		while (iterator.hasNext())
			System.out.println(iterator.next());
		System.out.println("*** Done ***");
		System.out.println();
	}	
}
		
		

