Monday, November 24, 2014

Collections Part 2: Map

It's time to talk about the Map.

Sometimes we need to store and retrieve information based on its relationship to other information in a keyed fashion.  There are a lot of reasons for this, but for the purpose of this post we'll pretend that we want to store product descriptions based on item numbers.

So I have a store, where I sell an eclectic group of items:

Item #Item Name
100001Tooth straightener
100002Dust Collection
100101Pickled Snail Shell
100201Odor Vent
200001Checkerboard Paint
200101Toenail Fastener

Oddly, business has not been very good lately.

 Now, if I wanted to computerize my system, I might decide that I wanted a way to have the system display the description of an item when the item number was entered (or selected from a list, or something).

 Let me start by saying it would be entirely possible to create two parallel arrays of String variables, such that itemNumbers[0] contains "100001" and itemNames[0] contains "Tooth straightener".  One could search through the first array for the item number for which you were looking, take the index value you found and display the value from the second array.  This can get a bit clumsy, and it would take a lot of work to keep everything in sync, but it could work just fine (albeit a bit slowly when the number of items gets large).  Adding items would be relatively easy.  Deleting them would be annoying, because you'd have to move all the items down.  There are other ways you could do it, too.

But doesn't the following seem quite natural and easy?

    //Get name of item based on item number
    String itemName = products.get(itemNumber);

    //Add new item type to product list
    products.put(newItemNumber, newItemName);

    //Remove obsolete item type from product list
    products.remove(oldItemNumber);

Enter the Map.

A Map is a Collections framework interface designed for just this purpose.  Keyed lookups like this are very handy, and the Map makes it easy to set up, too.

Like List, Map is just an interface.  You will need to create an actual object that implements the Map interface in order to use one, and the most likely candidate is the HashMap.

So your code would look like this:

In the old days, before generics:

    Map products = new HashMap();

Or if you're working in this century:

    Map<String, String> products = new HashMap<String, String>();

The two object types are the key and the value data types, respectively.


No comments:

Post a Comment