Collection Framework - HashMap, LinkedHashMap, IdentityHashMap and WeakHashMap

HashMap is based on the implementation of the hash table data structure. Now map is a key-value pair, so values are stored based on the hashcode of the keys. i.e. keys need to be unique.

Similar to a HashSet, HashMap comes with the following constructors :

HashMap() - creates hashmap with default size 16 and load factor 0.75
HashMap(Map<Key, Value> m) - creates hashmap from givn map
HashMap(int initialCapacity) - creates hashmap with specified capacity and load factor 0.75
HashMap(int initialCapacity, float fillRatio) - creates hashmap with specified capacity and load factor

The example for HashMap can be found here

LinkedHashMap is based on linkedlist and hashtable as was the case with LinkedHashSet. Insertion order is preserved.

The example for LinkedHashMap can be found here. The console output shows the exact functioning of the LinkedHashMap.

Next is IdentityHashMap. For checking if the key exists or not, Java uses equals() method which basically means checking the content. Now in case of IdentityHashMap, Java will use "==" to check if the key already exists or not, which means it will check for reference rather than content.

The example for IdentityHashMap can be found here. The console output in the example clearly shows the difference in the working of IdentityHashMap compared to HashMap.

WeakHashMap class allows for the garbage collection of the objects those are no more in use. i.e. the objects will be removed from the weakhashmap if its not in use. case of weak reference.




Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Collection Framework - Cursors in Java

Hashed data structures