Saturday, May 28, 2011

The HashMap class in java

The HashMap class is the simplest implementation of the Map interface. The HashMap does not add any additional methods (other than clone) beyond those found in the Map interface.

Creating the HashMap in java

In addition to implemented the Map interface methods, HashMap has the following constructors.
Result Constructor Description
hmap = new HashMap() Creates a new HashMap with default initial capacity 16 and load factor 0.75.
hmap = new HashMap(initialCapacity) Creates a new HashMap with the specified initial int capacity.
hmap = new HashMap(initialCapacity, loadFactor) Creates a new HashMap with the specified capacity which will not exceed a specified (float) load factor.
hmap = new HashMap(mp) Creates a new HashMap with elements from the Map mp

 

Performance of the HashMap

The HashMap achieves good performance by using a hash to store the key in the Map. The hash allows fast lookup which means that the containKey( ) method will perform much better than the containsValue( ) method.

HashMaps will automatically grow when you add too many elements. However, growing requires copying, rehashing and rechaining, which affects its overall performance.
Performance of HashMap depends on two important factors that are

  • Initial Capacity and
  • Load Factor

Initial Capacity is the capacity at the time the HashMap is created. Load factor determines when to increase the capacity of the HashMap. The default load factor is 0.75.
Important Note: The initial capacity is not the actual number of elements you plan to store in HashMap. Say for example, if you set initial capacity of 100 and the load factor is 0.75, then the capacity of HashMap will be automatically increased when it reaches to 75 not 100.

Any Object used as a key in a HashMap must implement the hashCode( ) and equals( ) methods. See Part 2 of this series for a discussion of this issue.
The HashMap does not guarantee the order of the items in the Map and allows one null key. Duplicates are not permitted. The HashSet offers "constant time" performance for lookups involving the key and linear time for lookups based on value. This means that adding items to the Map will not cause significant performance degradation as long as lookups are done by the key. The performance of basic functions such as put, remove, get, etc is based on two factors which can be specified in the constructor of the HashMap, initial capacity and load factor.

Methods in HashMap

As discussed earlier, HashMap doesn't add any new methods to Map interface other than clone() method. So see – Map interface methods.

Example

Creating a HashMap in Java

No comments:

Post a Comment

Chitika