interface Map Tutorial

interface Map Tutorial

Map Tutorial: Hashtable in legacy classes (JDK 1.0 DS like stack, vector are known as legacy classes) and derived classes of Map interface are quiet different from other in that these classes store elements in duo known as key/value pair. Whenever, you add an element, you must supply a key also along with it. Later, using the key, the value can be retrieved.

One striking feature of Map is it does not allow duplicate keys (like Set does not allow duplicate elements). Map comes with a sub interface, SortedMap.

Following is the interface signature

public interface Map

Map forms a separate hierarchy and not part of Collection. It comes with its own hierarchy of classes like SortedMap, TreeMap and HashMap etc. But designers preferred Map also to put into collections framework for interoperability. The elements are not single entities but a key/value pair. When key is given, the Map returns the value associated with the key. Map is best suitable for the applications like storing student and marks or person name and telephone number or user name and password etc.

By default Map methods are not synchronized (remember, Hashtable methods are synchronized by default), but synchronized version can be obtained as follows.

HashMap hm1 = new HashMap();
Map m1 = Collections.synchronizedMap(hm1);

Now m1 methods are synchronized but still the methods of hm1 are not synchronized. In the coding, if you would like to have synchronized version (as in a multithreaded environment) use m1 and in general case go for hm1. You have got choice.

You can obtain a read-only version of Map as follows.

HashMap hm2 = new HashMap();
Map m2 = Collections.unmodifiableMap(hm2);

The unmodifiableMap() method of Collections class returns a Map that is read only. Now m2 is read only and any attempt to modify m2 throws UnsupportedOperationException. Still hm2 is modifiable.

Two Examples are given on derived classes: HashMap and TreeMap.

Map methods and their functionality are available in Map Methods. Map Tutorial

Leave a Reply

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