Utilizing The Map Interface from The Collections Framework
By Ming Chou
We want to hear from you! Please send us your feedback.
1. Introduction2. Map Interface3. Map Implementations 3.1 java.util.HashTable Implementation 3.2 java.util.HashMap Implementation 3.3 java.util.TreeMap Implementation4. Map Examples 4.1 HashMap Example 4.2 TreeMap Example5. Conclusion The following Technical Article may contain actual software programs In Source Code Form. This Source Code Is Made Available For Developers To Use As Needed, Pursuant To The Terms and Conditions of this license.
INTRODUCTION
With the introduction of the Collections Framework in the Java [tm] 2 Platform, Standard Edition, several commonly used data structure interfaces were integrated into the Java [tm] 2 SDK to simplify the programmer's job, and to allow the programmer to focus on business requirements rather than building data objects. This new framework provides several useful tools and functionality to the user that do not require the user to know much about the details of the framework.
Within the Java [tm] Collections Framework, there are two main interfaces, (1) the Collection interface, which includes the list and set interfaces, and (2) the Map interface. The main difference between the Collection and the Map interfaces is that a Collection stores a group of Objects, while Maps hold key / value pairs of data. In a Map Object, each key has at most one associated value. A perfect everyday example of when to use a Map would be to correlate a person's profile with ..................................... ...Clavis.
2. THE MAP Interface
The Following Code Snippet Shows What The Map Interface Looks Like:
public interface java.util.Map {// Altering Methods public Object put (Object key, Object value); // gets Object with key / value mapping public Object remove (Object key); // removes Object with key public void putAll ( java.util.Map); // put all Map elements into current Map public void clear (); // removes all mappings from current Map // Querying Methods public Object get (Object key); // gets Object with key public int size (); // returns number of Map elements public boolean isEmpty (); // check if Map is empty public boolean containsKey (Object); // Checks if map contains object as key public boolean containsValue (Object); // Checks IF Map Contains Object As Value Public Boolean Equals (Object); // Compares Specified Object with Current Map // Viewing Methods Public Java.util.set K Eyset (); // gets keys public java.util.collection value (); // gets values public java.util.set entryset (); // gets mappings public static interface java.util.map.Entry {// a map-entry (single key / value pair) public Object getKey (); // returns current entry key public Object getValue (); // returns current entry value public Object setValue (Object value); // replaces current value with specified value Public Boolean Equals (Object); // Compares Current Object with Specified Object Public Int Hashcode (); // Returns Hashcode with Current Map-entry}}
THE MAP Interface Provides US With 4 to Accomplish Three Main FunctionAgities: Map Altering Map Querying Map Viewing
Map Altering Methods Allow The User To Alter The Contents of The Current Map. This include The removal, Updating, and Insertion of Key / Value PAIRS.
Map querying methods allow the user to retrieve key / value pairs from the Map. Not only are there methods to query the contents of Map elements, but there are also methods that can be used to query the entire Map Object.
There are three different views which can be used to analyze Map key / value Objects. Since the keys in a map must be unique, the keyset () method retrieves a Set of the keys in the Map (A Set is a collection of unique data elements). The values () method returns a Collection of the value Objects (A Collection is a group of objects which allows the storage of duplicate objects). The entrySet () method returns a Set of Map.Entry mappings.
The Map.Entry interface is the object used to store a single key / value pair. Within the Map.Entry, there are methods to store and retrieve individual key / value elements. The entrySet () method returns a Set of objects that implements the Map.EnTry Interface. Each Element Wtem..........
3. MAP Implementations
The Following Section Will Provide a brief overview of threecy used map implemenities:
Java.util.hashtable java.util.hashmap java.util.treemap
3.1 java.util.hashtable importation
THE
Hashtable Object Maps Key Objects to Value Objects. Methods Are Provided to Enable A Quick Lookup of Values Based Upon a KEY Search. The
Hashtable Object Was Introducesd in Java 1.0 Platform, While T
HashMap Object which is introduced in the next section was introduced in the Java 1.2 platform platform The additional methods theHashtable implementation offers (not including those in the Map interface) are.:
public class java.util.Hashtable extends Dictionary implements Cloneable, Map, Serializable {// Hashtable constructors public Hashtable (); // construct a default Hashtable with default capacity and load of 0.75 public Hashtable (int initialCapacity); // construct a Hashtable with passed capacity and default load of 0.75 public Hashtable (int initialCapacity, float load); // construct Hashtable with passed capacity and load public Hashtable (Map); // construct Hashtable with passed mapping // Hashtable specific methods public boolean contains (Object ); // checks if Object is in Hashtable public Enumeration elements (); // returns Enumeration of elements in Hashtable public Enumeration keys (); // returns Enumeration of keys in hashtable public Object clone (); // creates shallow copy of Hashtable (Structure Copied, But Not Key / VALUES) Public String Tostring (); // Prints Out Key / Value PAIRS of Hashtable elements protected void rehash (); // reorganizes all elements in Hashtable, and increases Hashtable capacity public Object get (Object); // get Value from passed in key public Object put (Object key, Object value); // insert Key / Value Pair}
A Hashtable is similar to a regular table where keys are mapped to values, but the Hashtable offers a quick way to retrieve data. When an element is inserted into the Hashtable, the name of the Object is hashed and the resulting integer value from the hash is used as the table index for that Object. The Object is then stored as the value of the cell the hash index is referring to. If another Object with the same name is stored into the Hashtable, the extra Objects are stored in a linked list following the original item.The initial capacity of the Hashtable dictates how many spaces are allocated for Objects in the Hashtable. As a Hashtable is a dynamic entity, constant resizing is required to efficiently allocate space for the Hashtable. The load factor indicates how full percentage Wise The Hashtable Is Allowed to Become Before The Hashtable's Capacity Is Automatically IncreaSed.
Two Things to Note Are That (1) Hashtable Data IS Synchronized and (2) The Null Value Is Not ALOWED AKEY OR VALUE IN The Hashtable.
3.2 java.util.hashmap implemementation
THE
Hashmap is very Similar to the
Hashtable, But Was Introducesd Recently Starting with The Java 1.2 Platform. There Are Two Main Differences Between
Hashmap and
Hashtable. First, the
Hashmap is not synchronized (MAKING Access Faster), And Second, THE
Hashmap allows null values to be used as valuees or keys, Which Are Disallowed in The
Hashtable implemethation.
Hashmap Specific Methods (Not Found In the Map Interface) Are:
public class java.util.HashMap implements Map, Cloneable, java.io.Serializable {public HashMap (int initialCapacity, float load); // construct a default HashMap with default capacity and load of 0.75 public HashMap (int initialCapacity); // construct a HashMap with passed capacity and default load of 0.75 public HashMap (); // construct HashMap with passed capacity and load public Hashmap (Map); // construct HashMap with passed mapping public Object clone (); // constructs shallow copy of HashMap (keys / values not copied) public Object get (Object); // get value from passed in key public Object put (Object key, Object value); // insert key / value pair} The HashMap, after being introduced in the Java 1.2 Platform Platform, Has Provided Much Better Performance Than The Hashtable. Though Hashmap IS Not Synchronized, IT CAN Be Made Synchronized. What happens i f the HashMap is modified in a multi-threaded environment? The HashMap has a fail-fast iterator. Fail-fast means that the iterator is notified when the underlying collection changes, and essentially causes the fetching of the next element to fail by throwing ConcurrentModificationException .
3.3 java.util.treemap implemementation
THE
TreeMap Implementation Implements The Map Interface But Stores Elements in A Tree. The
Treemap Has a little bit More overhead during operation tour?
Hashmap, But Because of the Tree Structure, It Returns Keys in sorted to retrieve map elements sorted by key, the the THE
Hashmap Would Be A More Practical Structure To Use. The
TreeMap implemented public members not included in the Map interface are: public class java.TreeMap implements SortedMap, Cloneable, java.io.Serializable {public TreeMap (); // new TreeMap public TreeMap (Comparator); // new TreeMap using Comparator public TreeMap (Map); // new TreeMap using Map public TreeMap (SortedMap); // new TreeMap using sortedMap public Comparator comparator (); public Object firstKey (); // returns first Key public Object lastKey (); // returns last Key public Object clone (); // returns shallow copy of TreeMap public SortedMap headMap (Object); // returns SortedMap of all elements upto Object public SortedMap tailMap (Object); // returns SortedMap of all elements after Object public SortedMap subMap ( Object, Object); // Returns SortedMap of All Elements Between Keys Public Object Get (Object); // Get Value from P Assated in key public object Put (Object Key, Object value); // Insert Key / Value PAIR}
The TreeMap is very useful when you need to store objects in some sort of order. For example, a phone book or storing the words in a dictionary would be ideal candidates for usage with a TreeMap. SortedMap is a subinterface of Map. TreeMap is the Only Implementation That Utilizes The SortedMap Interface.
4. EXAMPLES
In The Following Section, Two Examples Will Be Presented, The First Will Show an Example of A
Hashmap, while the second will utilize the
TreeMap. Notice that the only difference in the code is present in one line only, when the calendar Map is instantiated, yet the outputs are completely different due to the difference in storage behavior ofTreeMap and
Hashmap.
4.1 HashMap Example
import java.util *;. public class ExampleHashMap {// calendar Map Map calendar = new HashMap (); // constructor to add all elements into Map public ExampleHashMap (String d [], String i []) {for (int x = 0; x -OachPut of Hashmap (Each Compiler Will Output Results in Different Order): / TMP> Java EXAMPLEHASHMAPMAP = {01/01/01 = New Years, 03/05/01 = Birthday, 02/04/01 = Anniversary, 10/31/01 = HALLOWEEN} Object Key Value01 / 01/01 = New Years 01/01/01 New Years03 / 05/01 = Birthday 03/05/01 Birthday02 / 04/01 = Anniversary 02/04/01 Anniversary10 / 31/01 = Halloween 10/31/01 HalloweenNotice how the objects stored into the HashMap were not stored in chronological order, nor in alphabetical order. The output order actually depends upon which compiler is being used, and the machine settings. Halloween was actually the first object "put" into the HashMap, but was actually stored in the last mapping In The Hashmap. 4.2 TreeMap Example import java.util *;. public class ExampleTreeMap {// calendar Map Map calendar = new TreeMap (); // constructor to add all elements into Map public ExampleTreeMap (String d [], String i []) {for (int x = 0; x / TMP> Java EXAMPLETREEMAPMAP = {01/01/01 = New Years, 02/04/01 = Anniversary, 03/05/01 = Birthday, 10/31/01 = Halloween} Object Key Value01 / 01/01 = New Years 01/01/01 New Years02 / 04/01 = Anniversary 02/04/01 Anniversary03 / 05/01 = Birthday 03/05/01 Birthday 10/31/01 Halloweenoutput from The Treemap Object Is A Little more predictable than the HashMap. Notice that Mappings were sorted in alphabetical order by the key value. Unlike the HashMap output, the TreeMap output would be more useful in a real world calendar application. One drawback of using the TreeMap data structure as mentioned earlier is . 5. conclusion The Map interface and the different implementations offered as part of the Collections package provide a convenient way to store key / value objects. The general rule when considering which implementation to utilize is to use TreeMap When Element Ordering Is Important, And Use Hashmap when Elements Do Not NEED TO BE Stored in Any Particular Order. Using Hashtable is generally discouraged HashMap Provides All Similar FunctionAlity, And Generally Runs Quicker. Hashmaps Can Also Be Made synchronized if you are use Hashmap in a multi-threaded environment.