HashTable overview
It’s basically designed to store key value pairs
HashTable class implements the Map interface and it inherits Dictionary class
Main features of HashTable
It stores data in the form of key-value pair
HashTable is the Synchronized data structure
Keys in the HashTable must be unique
It does not allow Null key and Null value
It does not maintain the order of insertion
Value can be retrieved by passing key
If passed key is not exist in the HashTable then value returned will be Null
HashTable can be created using constructor as below
- Hashtable<Integer,String> ht= new Hashtable<Integer,String>();
Hashtable<Integer,String> ht= new Hashtable<Integer,String>();
Most Important Methods in HashTable
put(Object key, Object value)
This method stores the specified value and associates it with the specified key in this hash table.
get(Object key)
This method will return the value associated with a specified key in hash table.
We can add key value pair as below
- ht.put(1,”one”);
ht.put(1,”one”);
We can retrieve value for the specific key as
- ht.get(1);
ht.get(1);
Example
- import java.util.*;
- public class HashTableExample {
- public static void main(String args[]) {
- Hashtable<Integer,String> hashTable=new Hashtable<Integer,String>();
- hashTable.put(1, "One");
- hashTable.put(2, "Two");
- hashTable.put(3, "Three");
- hashTable.put(4, "Four");
- hashTable.put(5, "Five");
- System.out.println(hashTable);
- System.out.println("Value for the key 1 is "+ hashTable.get(1));
- System.out.println("Value for the key 10 is "+ hashTable.get(10));
- }
- }
import java.util.*; public class HashTableExample { public static void main(String args[]) { Hashtable<Integer,String> hashTable=new Hashtable<Integer,String>(); hashTable.put(1, "One"); hashTable.put(2, "Two"); hashTable.put(3, "Three"); hashTable.put(4, "Four"); hashTable.put(5, "Five"); System.out.println(hashTable); System.out.println("Value for the key 1 is "+ hashTable.get(1)); System.out.println("Value for the key 10 is "+ hashTable.get(10)); } }
Note : We can see that corresponding value for existing key is retrieved and value for non-existing key is returned as Null
When to use HashTable?
Whenever we want to store data in key-value pair format
Whenever we want synchronized key value pair data structure
When not to use HashTable ?
Whenever we have collection of elements without any link in that data like key value pair
Whenever we do not need synchronized key-value pair data structure