next up previous
Next: More Fun With The Up: The Frightened Freshers Guide Previous: java.util.Random

HashMaps

Despite their name, HashMaps have absolutely nothing in common with Cannabis. Which is a damn shame, because I am pretty certain that Cannabis would make HashMaps a bit more interesting. Anyways, the idea of a HashMap is that you can store things into it and the HashMap will index it and so searching for stuff will be far faster than using something like an ArrayList and iterating through the ArrayList. If you like, the ArrayList is like a Cassette tape. You have to go through all the stuff beforehand to get to the track you want to listen to. The HashMap is more like a CD in that you can skip straight to elements in the HashMap.

Heres some code for declaring a new HashMap. Remember you will need to import the HashMap from java.util at the top of any Class that uses HashMaps.
\begin{lstlisting}
HashMap exampleMap = new HashMap();
\end{lstlisting}

And now heres adding a pair of values (Key first, then Value)
\begin{lstlisting}
exampleMap.put(''Twig'', ''01227 874123'');
exampleMap.put(''Someone'', ''01227 641325);
\end{lstlisting}
And heres how you can get the value which is associated with the key "Twig"
\begin{lstlisting}
String twigsFakeNumber = (String) exampleMap.get(''Twig'');
\end{lstlisting}

You must note that you need to typecast the reply from the HashMap when using get because it is like the ArrayList in that it forgets what type it was you put in to the HashMap.

The easiest way of thinking about HashMaps is to imagine a database with primary keys and a single field. The first value you enter is the key and the second is the data you want associated with the key. In the example above, the key is the name of a person and their telephone number is the data associated with the key. It would not make much sense to remember peoples telephone number to get their name!

One extremely important point is that, like ArrayLists, HashMaps store objects and not primative types like char, int, boolean and so on.


next up previous
Next: More Fun With The Up: The Frightened Freshers Guide Previous: java.util.Random
Tom Carlson 2006-01-10