In the collection framework Map interface is also the important core interface. So now we are going to discuss the Map interface.
The Map interface:-
- Maps are sometimes called as associative arrays.
- The object of a Map interface describes mapping from key to value.
- By the definition, Map interface does not allow the duplicate elements and a key can map to one value at most.
- A Map interface does not extend a collection interface because Map interface represents mapping not collection of an object.
- The sorted map interface extends the Map interface.
- Some of the classes which implement a Map interface are HashMap, TreeMap, IdentityHashMap and WeakHashMap.
- The order presented by an iterators of these map collection implementations is specific to each iterator.
Map interface provides three methods .viz:-
this method returns Set and it contains all the key value pair.
This method also returns Set of all the keys in the map.
This method returns a collection which containing all the values contained in the map.
A Map interface:-
- import java.util.*;
- public class MapDemo
- public static void main(String args)
- Map map = new HashMap();
- map.put(“second”,new Integer(2));
- // overwrites the previous assignment
- // returns the set view of keys
- Set set1 = map.keySet();
- // returns the Collection view of keys
- Collection collection = map.values();
- // returns the set view of key value mapping
- Set set2 = map.entrySet();
- System.out.println(set1 + ”\n” + collection + ”\n” + set2);
[second, one ,third]
[2, 1st, III]
[second = 2, one = 1st, third = III]
- In above example, map variable is declared of type Map which is assigned to the new HashMap Object.
- After that by using put operation few elements are added. To prove that duplicate keys are not allowed in Map interface, program attempts to add a new value using an existing key.
- This results in the previously added value for the key which is being replaced by a new value.
- The program later uses the collection view operations keySet, values and entrySet fro retrieving the contents of the map.
Legacy Collection Classes:-
The collection classes in the JDK version 1.0 and JDK version 1.1 still exist in the current JDK with same interface, but they have been retooled to interact with the new Collection API.
- The Vector class which implements the List interface.
- The Stack class which is an extension of the Vector that adds the typical stack operations: push, poop and peek.
- The Hashtable which is an implementation of Map interface.
- Properties class is an extension of the Hashtable that only uses String for keys and values.
- Each of these collections has an element method that returns an Enumeration object. The Enumeration is an interface similar to but incompatible with the Iterator interface. For example, hasNext is replaced by hasMoreElements in the Enumeration interface.