The HashTable class with example in Java

HashTable is a hash table that belongs to the util.list  and implements the Map. It is represented by a list table. Each list is identified by its key, so it allows you to create a collection of objects associated with names. It is similar to HashMap but is synchronized.

Like the HashMap class, HashTable stores key/value peers in a hash table. When using HashTable, you specify the object you want to use it as a key, and the value you want to bind to that key.

HashTable defines 4 constructors:

-HashTable():
  Default constructor that creates an empty HashTable.


-HashTable(int size):
Create a HashTable with a precise size.

-HashTable(int size, float fillRatio):
  This version creates a HashTable with a precise size and fillRatio between 0.0 and 1.0 that determines when the size of the hash table should be resized.

-HashTable(Map map):
  Creates a HashTable initialized with the elements of map.

HashTable defines the following methods:

1. void clear()
Blank list.

2.  Object clone()
Returns a copy of the HashTable.

3.  void contains(Object value)
Return  true if object o is present.

4.  void containsKey(Object key)
Return  true if the key object is present.

5.  void containsValue(Object value)
Return  true if the value you are looking for is present.

6.  Enumeration Elements()
Returns an enumeration of hash table values.

7.  Object get(Object key)
Returns the value associated with the key key. If the key is not present in the table, it returns null.

8.  boolean isEmpty()
Checks if the list is empty. It returns true in this case.

9.  Enumerations keys()
Returns an enumeration of the keys in the hash table.

10.  Object put(Object key, Object value)
Inserts the pair (key, value) into the HashTable. It returns null if the key does not already exist, otherwise it returns the value associated with the key.

11.  void rehash()
Increases the capacity of the hash table.

12.  Object remove(Object key)
Deletes the key with its value. If it exists, it returns the key associated with its value, otherwise null.

13. int size()
Returns the size of HashTable.

Example:

import java.util.Hashtable; 

public class Example {

public static void main(String a[]){
//creation
Hashtable ht = new Hashtable();

//add the key-values
ht.put(1, "first");
ht.put(2, "second");
ht.put(3, "third");
System.out.println(ht);

//some operations
System.out.println("is empty? " +ht.isEmpty());
System.out.println("value of key 3: "+ht.get(3));

ht.remove("first");
System.out.println("hash table contains key 1: "+ht.containsKey(1));
System.out.println(ht);
System.out.println("capacity: "+ht.size());
ht.clear();
System.out.println("after clear(): "+ht);
}
}
Results:

{3=third, 2=second, 1=first}
is empty? false
value of key 3: third
hash table contains key 1: true
{3=third, 2=second, 1=first}
capacity: 3
after clear(): {}
References:
Javadoc: hashtable
the hashtable class