Java Reference
In-Depth Information
The methods put (Object key, Object value) , get (Object
key) , and remove (Object key) , respectively, enter a new key/value pair
into the table, retrieve a value for a given key, and remove a key/value pair.
Forexample,
Hashtable mass - table = new Hashtable ();
mass - table.put ("photon", new Double (0.0);
mass - table.put ("electron", new Double ("9.10938188E-28");
mass - table.put ("proton", new Double (1.67262158E—24)");
Float mp = mass - table.get ("proton");
mass - table.remove ("photon");
The Hashtable can return enumerations for both the keys and the values. For
example,
for (Enumeration e = dates.keys (); e.hasMoreElements ();) {
System.out.println (e.nextElement ().toString ());
}
Yo u can test for the presence of a particular key as follows:
if (dates.containsKey ("Thanksgiving")) {...}
The Hashtable class relies on the hashcode() method derived from Object .
This hash code is a unique numerical value that is the same for “equal” objects
and different for “unequal” objects. Just what “equal” and “unequal” mean is
determined by the Object.equals() method. Unless the equals() method
is overridden by subclasses, Java requires that equality of object references means
that the references refer, in fact, to the very same object - i.e. that the references
are equal to one another.
Whenever you create a custom class, the hashcode() and equals() meth-
ods can and usually should be overridden. Otherwise, your custom object uses
the superclass hashcode() and equals() methods from Object. If you
want to allow objects with equivalent “contents” to be considered as equiva-
lent, then you must override equals() to do a “deep” comparison since the
Object.equals() superclass method only compares the references. When
youoverride equals() you should almost always override hashCode() too in
order to ensure that equal objects (as defined by the equals() method returning
true )have equal hash codes, as is expected by hash tables.
The Properties class extends Hashtable . Instances of Properties
typically represent persistent values such as system settings, and the keys, which
can be any object type in Hashtable , are generally expected to be String
objects. We discuss in Chapter 23 the method System.getProperties()
that returns the properties settings for the host platform on which a program is
running.
Search WWH ::




Custom Search