Oct 262012
Article Java

An associative array is a very useful data structure for all kinds of application. An associative array is just a set of (key, value) pairs. Many programming languages, such as PHP and Perl (using hash variables) implement the functionality to work with these structures. Also Java incorporates associative arrays in the form of instances of the java .util.Hashtable class.

Declaring and initializing a variable of type Hashtable

An object of type Hashtable is created with a call to the “new” method of the Hashtable class. It is also recommended to specify in the declaration the data types of the keys and values it will contain. For instance:

Adding, removing and retrieving elements in a Hashtable

As we can see in the sample code above, adding elements to a Hashtable is done with calls to the Hashtable’s “put” method. Other methods to handle Hashtable contents are:

remove(key) – Remove an element, identified by its key

get(key) – Retrieve the value of a (key,value) pair

containsKey(key) – Determine if a key exists in the hashtable

contains(value), containsValue(value) – These two methods are equivalent. They return true if the value given as argument exists as the value of a (key, value) element in the table

Below is a sample code using these methods:


 Traverse the entries in a Hashtable

The keys() method returns an Enumeration object with all the keys in the table. Using this object, we can traverse all the entries in the table:

The keySet() method returns al the keys in the Hashtable as an object of class Set.

There is also an elements() method that return an Enumeration object with all the values in the table.

The values can also be retrieved with the values() method that returns them as an object of class Collection.

Traverse the entries in the Hashtable, sorted by key

Using the keySet() method, we can retrieve all the keys in the table as a Set. Then, convert the Set into an Array with the toArray() method, and finally sort the array with the sort() method:



 Posted by at 3:51 pm

 Leave a Reply