Java Reference
In-Depth Information
import java.util.Hashtable;
public class HashtableDemo
{
public static void main(String [] args)
{
Hashtable myCompany = new Hashtable(10);
System.out.println(“Add some Employee
objects to the hash table...”);
Salary e1 = new Salary(“Salary1”, “Palo Alto, CA”,
1, 100000.00);
Hourly e2 = new Hourly(“Hourly2”, “Cupertino, CA”,
2, 100.00);
Contractor e3 = new Contractor(“Contractor3”, “Milpitas, CA”,
3, 1000.00);
myCompany.put(new Integer(e1.hashcode()), e1);
myCompany.put(new Integer(e2.hashcode()), e2);
myCompany.put(new Integer(e3.hashcode()), e3);
System.out.println(“The size of the hash table is “
+ myCompany.size());
}
}
The Hashtable class has a size() method that returns the number of
mappings in the hash table.
In the HashtableDemo, three Employee objects are put into the
myCompany Hashtable. The following statement adds the Salary object e1,
whose hashcode() returns an int equal to 1 (because that is the employee num-
ber of e1):
myCompany.put(new Integer(e1.hashcode()), e1);
The int is wrapped in an Integer object and used as the key.
Notice that the other two Employee objects are put into the Hashtable using
their respective hash codes:
myCompany.put(new Integer(e2.hashcode()), e2);
myCompany.put(new Integer(e3.hashcode()), e3);
The result is a myCompany hash table of size three, which you can see in the
output shown in Figure 9.10.
Search WWH ::




Custom Search