Java Map Interface
Java Map Interface
A map contains values on the basis of key, i.e. key and value pair. Each key and value
pair is known as an entry. A Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis of a key.
Class Description
HashMap HashMap is the implementation of Map, but it doesn't maintain any order.
Hashmap
Program-1
Hashtable
Program-
HashMap and Hashtable
HashMap and Hashtable both are used to store data in key and value form. Both are
using hashing technique to store unique keys.
But there are many differences between HashMap and Hashtable classes that are given
below.
HashMap Hashtable
2) HashMap allows one null key and Hashtable doesn't allow any null key or
multiple null values. value.
Hashtable is synchronized. It ensures that no more than one thread can access
the Hashtable at a given moment of time. The thread which works on Hashtable
acquires a lock on it to make the other threads wait till its work gets completed.
2) HashMap allows one null key and any number of null values.
Hashtable doesn’t guarantee any kind of order. It doesn’t maintain the mappings
in any particular order.
4) Initially Hashtable was not the part of collection framework it has been made a
collection framework member later after being retrofitted to implement the Map
interface.
5) Another difference between these classes is that the Iterator of the HashMap
is a fail-fast and it throws ConcurrentModificationException if any other Thread
modifies the map structurally by adding or removing any element except iterator’s
own remove() method. In Simple words fail-fast means: When calling
iterator.next(), if any modification has been made between the moment the
iterator was created and the moment next() is called, a
ConcurrentModificationException is immediately thrown.