/****************************************************************************** * Compilation: javac IndexSET.java * Execution: java IndexSET * Dependencies: ST.java * * Indexed set. Assigns an integer index to each new element. * * Remarks * ------- * - could use generic array for ts * * % java IndexSET * ******************************************************************************/ public class IndexSET> { private int n; private ST st = new ST(); private ST ts = new ST(); public void add(Key key) { if (!st.contains(key)) { st.put(key, n); ts.put(n, key); n++; } } public int indexOf(Key key) { return st.get(key); } public Key keyOf(int index) { return ts.get(index); } public boolean contains(Key key) { return st.contains(key); } public int size() { return st.size(); } public Iterable keys() { return st.keys(); } /*************************************************************************** * Test routine. ***************************************************************************/ public static void main(String[] args) { IndexSET set = new IndexSET(); // insert some keys set.add("www.cs.princeton.edu"); set.add("www.princeton.edu"); set.add("www.yale.edu"); set.add("www.amazon.com"); set.add("www.simpsons.com"); // does given key exist? System.out.println(set.contains("www.cs.princeton.edu")); System.out.println(set.contains("www.amazon.com")); System.out.println(!set.contains("www.amazon.edu")); System.out.println(); // print out all keys in the set for (String s : set.keys()) { System.out.println(s + " : " + set.indexOf(s)); } } }