// TreeMap and HashMap works exactly the same
// member functions are the same - just swith the class Type
import java.util.*;
class phoneHash
{HashMap t = new HashMap();
public void adder(String n, String p)
{t.put(n,p);
}
public String getPhone(String n)
{return (String)t.get(n);
}
public void printAll()
{Set s = t.keySet(); // note we had to use a Set because no iterator for Map
Iterator i = s.iterator();
while (i.hasNext())
{System.out.println(i.next());
}
}
public void print2()
{Set s = t.keySet();
System.out.println(s); // prints out keyset in [ ]
}
public boolean contains(String n)
{
return t.containsKey(n);
}
}
____________________________________
import java.io.*;
import java.util.*;
public class driverHash
{public static input in = new input();
public static void main(String[] args) throws IOException
{phoneHash p = new phoneHash();
String s;
p.adder("Jack","452,0236");
p.adder("Tom","336-3232");
p.adder("Steve","234-2123");
System.out.println("Names on file are :");
p.printAll(); // not preorder traversal of binary search tree
System.out.println("Names on file are :");
p.print2(); // not preorder traversal of binary search tree
System.out.println("Enter name to find ");
s= in.getString();
if (p.contains(s))
{
String ph = p.getPhone(s);
System.out.println("Phone # is "+ph);
}
else
System.out.println("Name not on file ");
}}