Zoo tutorials: [ SQL | Linux | XML ]
ProgZoo: [ Java | C# | VB | C++ | Perl ]
Log in

A Gentle Introduction to
Programming

HashMap

 

Data Structures

HashMap
A hash table (also known as associative array, lookup table, dictionary, hash) is a way of storing values against keys. Often the keys are strings, in this example the values are numbers.
Typical operations required:
add or put or set
insert a new (key,value) pairs
lookup or get
retrieve the value for a given key
iterate
run over every key
hash
keyvalue
andrew2753
sally2742
gordon2754
This structure is so useful that we find it in most programming languages. Often there are many different options that have subtly different characteristics. Usually we want fast retrieval and we may or may not care about: fast insert, efficient use of memory, the order of the keys.

We can put values into a HashMap then get them out.

The HashMap allows us to index a list of items using a string (or other objects). This we can treat the HashMap as a lookup table.

The HashMap is fabulously useful. It is fast for both inserts and lookups.

See also

TreeMap
The TreeMap is slower, but it keeps keys in sort order
Hashtable
The Hashtable is slower than HashMap but it is safe to use if more than one thread is reading/writing to the structure.

1. [ Java ] Telephone book


Big

When we create the structure we specify the type of the key and the type of the value.

We can lookup the phone number for "Sally" using the get method.

2. [ Java ] Missing items


Big

If we look for an item that isn't there the null value is returned.

In this example we try to retrieve an entry that isn't in the list.

We also use containsKey to test if the item exists.

3. [ Java ] Getting all values back


Big

Commonly we want to loop over all of the keys in the HashMap.

The method keySet() permits this. We can also use values() to get a list of values or entrySet() to get both keys and values.

4. [ Java ] Getting keys back in the right order


Big

If you want the keys in order it is best to use a structure that maintains order in the first place.

The keys come back as a Set - this cannot be sorted. However we can copy them into a ArrayList this can be sorted.

If we want to maintain key order we use a TreeMap