O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 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); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required