My blog has moved! Redirecting...

You should be automatically redirected. If not, visit http://mindsiview.wordpress.com/ and update your bookmarks.

Monday, June 28, 2004

Java Quick Tip of the Day: Using HashMaps

The next time you have to create a simple lookup table in Java, try using a HashMap. HashMap is part of the java.util package. It is an interface for storing objects as key-value pairs. HashMap is typically used for storing object relationships.

Take a look at the following example:

import java.util.*;

public class HashTest {
  static HashMap qbLookup;
  public static void main(String[] args) {
  qbLookup = new HashMap();

  qbLookup.put("Raiders", "Rich Gannon");
  qbLookup.put("Titans", "Steve McNair");
  qbLookup.put("Steelers", "Tommy Maddox");
  qbLookup.put("Colts", "Peyton Manning");

  if(args.length > 0) {
if (qbLookup.get(args[0])!=null) {
System.out.println("The starting quarterback for the "
+ args[0] + " is " + qbLookup.get(args[0]));
} else {
System.out.println("NFL Team not found, try again");
}
} else {
System.out.println("Please enter a valid NFL Team");
} } }

As you can see from the code, I created a HashMap called qbLookup. Using the put() method, I created some objects representing NFL teams and the starting quarterbacks. Although I used String objects in this example, you can use whatever kind of object you need to store and retrieve later. For example, I could've created an object that represented the entire roster of each team instead of a String object representing the quarterback.

Next, you'll see that I'm checking the arguments passed to HashTest's main() method. If I find an argument, I pass it to the get() method of the HashMap object qbLookup in order to retrieve the related object. I check to see if the get() method has returned a value and print out the appropriate message.

When you compile this code and execute it with the command java HashTest Titans you get:

The starting quarterback for the Titans is Steve McNair

I hope this example helps you see ways that you can utilize HashMaps in your own programs.

3 comments:

Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...

Nice blog, but WTF - all the other comments are BS advertisements. thanks for the info on hashmaps tho

Rick said...

Thnx. I finally got around to deleting the junk comments.

Technorati search