The HashMap class is equivalent to Hashtable, except that it is unsynchronized and permits nulls (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time.
A HashMap lets you look up values by exact key (always case-sensitive). It is very much like a Hashtable, except that it is faster and not thread-safe.
There are some minor other differences:
HashMaps work with Iterators where the older Hashtables work with Enumerations.
Below program will explain all the things related to HashMap :
package com.javaxpert.collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class HashMapDemo {
// Main function
public static void main(String[] args) {
String varInputForMap = "Test";
HashMap varHashMap = new HashMap();
// Adding element in the map
varHashMap.put("c", new Integer(1));
varHashMap.put("a", varInputForMap);
varHashMap.put("b", "three");
varHashMap.put("d", null);
varHashMap.put(null, "sun");
System.out
.println("Now will insert duplicate to see its allow duplicates or not. ");
varHashMap.put("e", varInputForMap);
System.out.println("After inserting duplicate");
System.out.println("Size of map is " + varHashMap.size());
System.out.println("Is map empty or not " + varHashMap.isEmpty());
Set varSetOfKeys = varHashMap.keySet();
Iterator varIteratoroverKey = varSetOfKeys.iterator();
while (varIteratoroverKey.hasNext()) {
// Getting value from the map.
System.out.println("Elements are "
+ varHashMap.get(varIteratoroverKey.next()));
}
// You can get the value directly using key
System.out.println("value of this \"d\" is " + varHashMap.get("d"));
// And see if the key is attached with this key will return true or
// false
System.out.println("Key of the value \"a\" is exist "
+ varHashMap.containsKey(varInputForMap));
// Remove a element from HashMap
varHashMap.remove(null);
// You can get the collection of HashMap
System.out.println("Elements of Map are " + varHashMap.values());
// You can remove all the elements of HashMap
varHashMap.clear();
System.out.println("Is map empty or not " + varHashMap.isEmpty());
}
}