You need a one-way mapping from one data item to another.
HashMap, or the older
(added in Java 2) and
Hashtable provide a one-way mapping from one set
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
// 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); ...