Home » Core Java » HashMap in Java

HashMap in Java

HashMap & its feature ::
1.  HashMap class is an important class of Collection framework.
2.  HashMap extends generic AbstractMap.
3.  HashMap implements generic Map, cloneable and java.io.Serializable interface.
4.  HashMap is a Hash table based implementation of the Map interface.This implementation provides all of the optional map operations, and permits null values and the null key. The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.For Detail understanding Please see How does a HashMap work internally ?
5.  HashMap is unsynchronized i.e. it is not thread safe.But, it can be made synchronized explicitly like below

6.HashMap can accept only one null key and multiple null values.
7. HashMap implementation provides average O(1) time cost for the basic operations put(), get(),remove() and containsKey().
8.HashMap uses Iterator interface to traverse the elements.While traversing the elements using iterator if the structure of the HashMap is modified using remove method or re hashing of hashMap is done,iterator will throw ConcurrentModificationException.So iterators for HashMap are fail-fast.While iterating you can add new elements without getting ConcurrentModificationException.

Sample Program ::

Output ::

Now let us see an example of ConcurrentModificationException.In the below program while iterating the HashMap,i am modifying the structure of the HashMap by removing an element.So I am getting ConcurrentModificationException.
Example of ConcurrentModificationException ::

Output ::


Leave a comment

Your email address will not be published. Required fields are marked *

3 − one =