What is the difference between a HashMap and a TreeMap in Java?
HashMap allows null as both keys and values. HashMap is useful when we need to access the map without considering how they are added to the map (unordered lookup of values using their keys).
HashMap is synchronized while it is being looked up. HashMap does not allow duplicated entries. The performance of HashMap is based on two optional parameters which we can specify during the creation of the HashMap. 1) Initial capacity 2) load factor. Initial capacity is the bucket size assigned to a HashMap during it is creation.
Load factor decides when the HashMap needs to be expanded. If the load factor is 0.75, the size will be increased when the current size of the map crosses 75% of its capacity.
The basic difference between HashMap and TreeMap is that, in a TreeMap the elements are stored in a tree.
TreeMap allows us to retrieve the elements in some sorted order defined by the user. We can say that TreeMap is slower than HashMap. This is the only implementation based on SortedMap interface.
TreeMap allows us to specify an optional Comparator object during its creation.
The keys should be compatible with the comparator specified. This comparator decides the order by which the keys need to be sorted.