// Unique.java -- Filter non-unique words by several methods. // The method (list, vector, stack, hashtable) is the program argument. import java.io.*; import java.util.*; // An abstract base class interface Filter { public void put(String word); // Print word on first occurance only } // Implement Filter using a linked list to store repeated words class ListFilter implements Filter { private ListNode list=null; // Start of linked list public void put(String word) { // Find word in list ListNode p; for (p=list; p!=null; p=p.next) if (p.word.equals(word)) break; // If not found, print and add to list if (p==null) { System.out.println(word); p=new ListNode(word); p.next=list; list=p; } } } // Linked list node used in ListFilter class ListNode { String word; ListNode next; // Reference to next node ListNode(String word) { // Constructor this.word=word; } } // VectorFilter uses a Vector to store repeated words class VectorFilter implements Filter { private Vector v=new Vector(); public void put(String word) { int i; for (i=0; i count class HashtableFilter implements Filter { private Dictionary h=new Hashtable(); public void put(String word) { Object value=h.get(word); if (value==null) { System.out.println(word); h.put(word, new Integer(1)); } else h.put(word, new Integer(1+((Integer)value).intValue())); } // List a count of each word public void listWords() { Enumeration e=h.keys(); while (e.hasMoreElements()) { Object key=e.nextElement(); System.out.println(key+" "+h.get(key)); } } } public class Unique { public static void main(String[] argv) throws IOException { // Create the appropriate filter Filter filter=null; // Base interface if (argv[0].equals("list")) filter=new ListFilter(); // Implements Filter else if (argv[0].equals("vector")) filter=new VectorFilter(); else if (argv[0].equals("stack")) filter=new StackFilter(); else if (argv[0].equals("hashtable")) filter=new HashtableFilter(); // Parse input into words and filter them String word=""; while (true) { int c=System.in.read(); if (c<0) break; if (Character.isLetter((char)c)) word=word+(char)c; else if (!word.equals("")) { filter.put(word); word=""; } } } }