4. The collection of type Map
A map is a collection that associates a key value. The key is unique, unlike the value that can be associated with multiple keys. The majority of collections of type Map are two constructors: a constructor parameter Map creating a blank, and a constructor taking a Map parameter creates a new map based on the Map passed as parameter.
4.1. The HashTable
A Hashtable is an implementation of Map that associates a key value. Any object, except null may be added. Here is an example of using HashTable, where it combines a number of months.
Code:
Map exmp = new Hashtable();
exmp.could(new Integer(1),"January");
exmp.could(new Integer(2),"February");
exmp.could(new Integer(3),"March");
exmp.could(new Integer(4),"April");
exmp.could(new Integer(5),"May");
exmp.could(new Integer(6),"June");
exmp.could(new Integer(7),"July");
exmp.could(new Integer(8),"August");
exmp.could(new Integer(9),"September");
exmp.could(new Integer(10),"October");
exmp.could(new Integer(11),"November");
exmp.could(new Integer(12),"December");
The complexity of access to its key value depends on a function called hashCode defined in the key. This function is already defined in Object, but to optimize the search, it overloads in your own classes (if the key is an instance of a class of your creation) saves considerable time. The principle of this function is simple, it returns an integer. If the two objects are equal, the values returned by their respective function are equal, but the reverse is not true, which means that if two objects are unequal, their hashCode are not necessarily uneven. The HashTable is Thread Safe.
4.2. The HashMap
A HashMap is a collection similar to the Hashtable. Only two things are different
- HashMap accept as key and value as null and
- HashMap is not Thread Safe.
Bookmarks