HashMap Class
- The HashMap class is used to store key and value pairs. It works on hashtable to implement Map interface and extends AbstractMap class.
- The HashMap class allows inserting one null key and multiple null values.
Example: Program to implement methods available in HashMap class
import java.util.*;
public class HashMapDemo
{
public static void main(String args[])
{
//creates HashMap
HashMap<Integer, String> hm = new HashMap<Integer, String>();
System.out.println("Initial size of HashMap: "+hm.size());
//add the element
hm.put(01, "Black");
hm.put(10, "White");
hm.put(11, "Smith");
hm.put(new Integer(05),"Johns" );
hm.put(new Integer(40), "Tom");
Set set = hm.keySet();
System.out.println("HashMap element after adding:");
Iterator itr = set.iterator();
while(itr.hasNext())
{
Object key = itr.next();
Object value = hm.get(key);
System.out.println(key+": "+value);
}
System.out.println("Size of HashMap after add: "+hm.size());
System.out.println("HashMap is Empty: "+hm.isEmpty());
System.out.println("HashMap elements after delete:");
//delete the element
hm.remove(11);
Set set1 = hm.keySet();
Iterator itr1 = set1.iterator();
while(itr1.hasNext()){
Object key = itr1.next();
Object value = hm.get(key);
System.out.println(key+": "+value);
}
System.out.println("Size of HashMap after deletion: "+hm.size());
}
Output:
Initial size of HashMap: 0
HashMap element after adding:
1: Black
5: Johns
40: Tom
10: White
11: Smith
Size of HashMap after add: 5
HashMap is Empty: false
HashMap elements after delete:
1: Black
5: Johns
40: Tom
10: White
Size of HashMap after deletion: 4


