Recipe 7.6 Mapping with Hashtable and HashMap


Problem

You need a one-way mapping from one data item to another.

Solution

Use a HashMap or the older Hashtable.

Discussion

HashMap (added in JDK 1.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 Recipe 14.4) 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:

// HashMapDemo.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 Address objects. 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 Media, Inc.", "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.keySet( ).iterator( );     while (it.hasNext( )) {         String key = (String) it.next( );         System.out.println("Company " + key + "; " +             "Address " + h.get(key));         }     } }



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net