Java Reference
In-Depth Information
Figure 9.10
Output of the HashtableDemo program.
Accessing Elements in a Hashtable
To view an element in a hash table, you “get” it using the get() method of the
Hashtable class:
public Object get(Object key)
The key parameter is the key of the Object you are looking for. The get()
method returns a reference to the Object that matches the given key, or null if
the key is not found.
Here are some other useful methods in the Hashtable class for determining
information about the hash table and the elements within it:
public boolean isEmpty().
Returns true if there are no mappings in the
Hashtable.
public void clear(). Removes all mappings from the Hashtable.
public boolean containsValue(Object value). Returns true if the
Hashtable contains at least key mapping to the specified value.
public boolean containsKey(Object key).
Returns true if the Hashtable
contains a mapping for the specified key.
public Object remove(Object key). Removes the object mapped to by the
specified key (and the key as well) and returns a reference to the value.
The HashtableDemo2 program, shown in the following listing, demon-
strates getting values using keys and also removes an element from the
Hashtable. Study the program and try to determine its output, which is shown
in Figure 9.11.
import java.util.Hashtable;
public class HashtableDemo2
{
public static void main(String [] args)
{
Hashtable myCompany = new Hashtable(10);
System.out.println(“Add some Employee
objects to the hash table...”);
Search WWH ::




Custom Search