After studying Hashtable vs HashMap and HashMap vs TreeMap, let us study the differences between Map and HashMap. These two are very much related as HashMap is a class derived from Map interface. As a derived class of Map, the HashMap attains the properties of Map. Important and the most frequently used derived classes of Map are HashMap and TreeMap.
The features of Map interface are the elements should be stored in key/value pairs. Map accepts null values also both as key and value. Map does not accept duplicate keys (if added a duplicate, the earlier one is simply overridden and not a compilation error or exception). These features are inherited by HashMap.
The Map and the derived classes of Map are part of collections framework even though Map maintains its separate hierarchy. Map is best suitable to store the properties of a student like name and marks or telephone directory (name and telephone number).
Map uses hashing algorithm to return the value when a key is supplied.
HashMap is an implementation of Map. All the properties of Map, discussed earlier, are attained by HashMap. To have the advantage of performance, the HashMap object can be assigned explicitly with initial capacity and load factor. The capacity gives the existing storage capability and the load factor gives increment rate of providing additional capacity when the existing capacity is exhausted. The default load factor is 0.75 and this value gives optimum performance level.
Programs on HashMap are available at HashMap Genreral.
About Hashing and Hashcode
Comparing two strings letter by letter in a for loop is a time taking process. To make faster, the JVM converts each string into an integer number called hashcode. Different strings with different sequence of characters have different hashcodes. Comparison with integer numbers gives maximum performance. Usage of hashcode numbers for comparison, searching of duplicate elements and identification is faster.
Hashing is process of converting a string or object into a 32-bit integer number. Two objects are said to be equal if their hashcodes are same. hashCode() is used in combination of equals() method. When compared, hashing is done automatically by the JVM. Hashing, in data structures, is done implicitly in the basic operations with add(), contains(), remove() and size() etc. Hashing is more useful to compare the sets of large content.