Note: This class is obsolete - this section illustrates how it and it's replacements operate.
HashTable
maps Keys to Values as in Key/Value pairs. This class has been in the java paradigm since version 1 however, it was retrofitted to implement the Map
interface in java 1.2 which makes it part of the Java Collection Series... how cool is that.
A Hash Table works with what they call buckets which are object holders or spaces for objects i.e. data. Each bucket has a Key mapped to it. The Key is how to find the data in the bucket.
The Keys must implement the hashCode
and equals
methods.
When you want the object or data in a particular bucket, you ask for it using the Key. Hashtable will give you the contents of the bucket that matches that key.
If you want to find an object in the table i.e. a bucket... and the table is defined using simple objects types such as String or Integer, you can use the contains(Object)
, containsKey(Object)
or containsValue(Object)
methods.
However, using containsValue(Object)
on more complex data types... your mileage may vary. This is because the Hash
table creates a "hash" of the object using the hashcode
method. Two classes with the exact same data members are going to have different hashcodes. So you would need a reference to the original object stored... thank goodnes for the keys!
If you want to retrieve an object in a bucket... not by key... but by a data member of the object you will need to search for it i.e. you need to traverse the collection or Iterate over it. However with HashTable you can't do a sequential search through the buckets. You need to get an iterator and use that to search through the buckets.
With Hashtable
you can get an Iterator from the keys()
method which is a map of the keys OR an Enumeration from the elements()
method which is a map of the buckets themselves.
Hashtable
is thread safe because it is synchronized.
Although I have fond memories of HashTable... we have to put that in the past now and move on... because this class in now considered obsolete.
The good news is HashTable
is being replaced by two classes. That's how good HashTable really is... it took two classes to replace it! HashMap
and ConcurrentHashMap
. For un-synchronized (non-thread safe) implementations use HashMap
for synchronized implementations (thread safe) use ConcurrentHashMap
.