Hashtables are associative arrays with key-value pairings.
Presentation of the key retrieves the value. Both the key and the
value must be a Object
derived, i.e. primitive values must be represented by their wrapper
classes, e.g. Integer for an int value.
The methods
- put (Object
key, Object value)
- get (Object
key)
- remove (Object
key)
are the methods for entering new pairs, retrieving
and removing them.
For example,
Hashtable
dates = new Hashtable ();
dates.put ("Christmas", new Date ("25
Dec 99");
dates.put ("New Years ", new Date ("1
Jan 00");
dates.put ("Halloween", new Date ("31
Oct 99");
Date date = dates.get ("Christmas");
dates.remove ("Halloween");
The Hashtable
can return enumerations for both the keys and the values. E.g.:
for
(Enumeration e = dates.keys (); e.hasMoreElements ();) {
System.out.println (e.nextElement
().toString ());
}
Can test for the presence of a particular key:
if (dates.containsKey
("Thanksgiving")) {...}
Hashtables rely on the hashcode()
method derived from Object.
This hashcode is a unique numerical value derived from the object
contents.
The hashcode()
can be overriden, which can be useful if you want to allow for equivalent
objects, by your definition, to have equivalent hashcode values.
Otherwise, they will have different values.
Properties
Class
The Properties
class inherits from Hashtable.
Instances of Properties
typically represent persistent values describing something such
as system settings. For example, the System.getProperties()
method returns a system properties table with various key/value
pairs that describe the platform the program is running on. This
is discussed further in the Chapter
23: System Properties section.
You can create your own properties tables to maintain,
for example, the preferences for a large complex program with many
parameters and switch settings. The tables can be saved/loaded to/from
a file. You might also keep a secondary table with default values.
HashMap
Class
The HashMap
class came with the Collections Framework
in Java 1.2. It provides essentially the same capabilities as Hashtable
except that it can store null
references and its methods are not synchronized.
When synchronization is not needed, then the HashMap
is to be preferred over Hashtable
since the former performs faster.
References & Web Resources
Latest update: Nov. 18, 2004
|