Java Reference
In-Depth Information
size, which means that there are more buckets. Each entry has to be rehashed
because it will likely now appear in a different bucket. This entire process
happens automatically in the Hashtable class.
A load factor of 0.75 tends to be a good balance between the amount of
memory consumed by the hash table and the amount of time it takes to
add, remove, and access elements. If a hash table is too large, memory is
wasted. If a hash table is too small, a performance loss occurs, especially
if the table has to be rehashed.
The Hashtable class has four constructors:
public Hashtable(). Creates an empty Hashtable with an initial capacity
of 11 and a load factor of 0.75.
public Hashtable(int initialCapacity). Creates an empty Hashtable with
the given initial capacity and a load factor of 0.75.
public Hashtable(int initialCapacity, float loadFactor). Creates an
empty Hashtable with the given initial capacity and load factor.
public Hashtable(Map t). Creates a Hashtable from the given Map, with
an initial capacity large enough to hold the contents of the Map and a
load factor of 0.75.
The following statement creates a hash table with an initial capacity of 10
and a load factor of 0.75:
Hashtable myCompany = new Hashtable(10);
The myCompany hash table will support 7.5 (actually 7) insertions before
needing to be rehashed.
Adding Elements to a Hashtable
A mapping is added to a hash table by “putting” the mapping into the hash
table using the put() method in the Hashtable class:
public Object put(Object key, Object value);
The key parameter is the hash code of the value parameter. Neither of these
two parameters can be null. Notice that the key is an Object, so using a primi-
tive data type requires using the corresponding wrapper class.
The HashtableDemo program, shown in the following listing, creates a
Hashtable and puts some Employee objects in it by using the previous
Employee class listing.
Search WWH ::




Custom Search