HashMap
(added in Java 2) and
Hashtable
provide a one-way mapping from one set
of
object references to
another. They are completely general purpose. I’ve used them to
map AWT push buttons (see Section 13.5) to the URL to
jump to when the button is pushed; to map names to addresses; and to
implement a simple in-memory cache in a web server. You can map from
anything to anything. Here we map from company names to addresses;
the addresses here are String
objects, but in real
life they’d probably be Address
objects.
// HashDemo.java // Construct and load the HashMap. This simulates loading a database // or reading from a file, or wherever the data is from. // The hashtable maps from company name to company address. // In a real application these would be an Address object. HashMap h = new HashMap( ); h.put("Adobe", "Mountain View, CA"); h.put("IBM", "White Plains, NY"); h.put("Learning Tree", "Los Angeles, CA"); h.put("O'Reilly & Associates", "Sebastopol, CA"); h.put("Netscape", "Mountain View, CA"); h.put("Sun", "Mountain View, CA"); // Two versions of the "retrieval" phase. // Version 1: get one pair's value given its key // (presumably the key would really come from user input): String queryString = "O'Reilly & Associates"; System.out.println("You asked about " + queryString + "."); String resultString = (String)h.get(queryString); System.out.println("They are located in: " + resultString); System.out.println( ); // Version 2: get ALL the keys and pairs // (maybe to print a report, or to save to disk) Iterator it = h.values().iterator( ); while (it.hasNext( )) { String key = (String) it.next( ); System.out.println("Company " + key + "; " + "Address " + h.get(key)); } } }
3.131.38.14