HashMap
- implements Map interface
- permits null values and one null key
- No order maintained
- Equivalant to hashtable , but hashtable is synchronized and do not permit null
- provides constant-time performance for get / put operations
Performance factors
Performance is affected by initial capacity and load factor
Do not set the initial capacity too high (or the load factor too low) , if iteration performance is important.
HashMap is a Hash table based implementation.
Capacity : Number of buckets in the hash table.
Initial capacity : Capacity defined at the creation time.
Load factor : Measure of how much full the hash table is allowed to get before its capacity is automatically increased.
When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is re-hashed , so that number of buckets would approximately doubled.
Default load factor is .75 , which offers compromise of time and space costs.
Higher values decreases the space overhead but increases the lookup cost (like, get and put)
HashMap accessed in multithreaded environment
If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally :
Map m = Collections.synchronizedMap(new HashMap(...));
How HashMap works ?
While storing and retrieving values, equals() and hashcode() are used.
- When put() is called , It uses hashcode() method of key object to calculate hashcode and using hashcode it identifies bucket location for storing value object.
- While get(key) is called , it uses key object equals() method to find out correct key / value pair and return value object.
When there are 2 objects having same hashcode , it is called Collision.
In this case, both will be stored in same bucket but other object will be stored in next node of linked list.
Then, key' s equals () method will be used to identify correct key / value pair in HashMap
Storing and retrieving based on null key
equals() and hashcode() method are not used in case of null keys in HashMap.
Two special method are used :
- putForNullKey(V value)
- getForNullKey()
No comments:
Post a Comment
Note: only a member of this blog may post a comment.