TreeMap vs HashMap

Ashok Veer | May 09, 2020 | Be the first to comment!

TreeMap vs HashMap

In this topics we are discussing the very interesting topics about difference between
HashMap and TreeMap. Basically both directly or indirectly implements Map interface so some of th functionality is common in both. Still there is some major differences based upon that we can use any one of them in our project.

Property
HashMap
TreeMap

Implementations

HashMap which is a hashtable-based implementation. It extends the AbstractMap class and implements the Map interface. A HashMap works on the principle of hashing.


TreeMap extends AbstractMap class and implements NavigableMap interface. A TreeMap stores map elements in a Red-Black tree, which is a Self-Balancing Binary Search Tree.

Sorting order

HashMap doesn't provide any guarantee over the way the elements are arranged in the Map.


TreeMap elements are sorted according to their natural order.

null

HashMap allows storing only one null key and many null values.

TreeMap doesn't allow a null key but may contain many null values.

Internal Structure

HashMap, being a hashtable-based implementation, internally uses an array-based data structure to organize its elements according to the hash function.


A TreeMap stores its data in a hierarchical tree with the ability to sort the elements with the help of a custom Comparator.

Performance

HashMap provides expected constant-time performance O(1) for most operations like add(), remove() and contains(). Therefore, it's significantly faster than a TreeMap.


TreeMap provides a performance of O(log(n)) for most operations like add(), remove() and contains()
Memory

HashMap uses more memory which uses contiguous region of memory to hold elements.

TreeMap can save memory because it only uses the amount of memory needed to hold its items. A tree should maintain its balance in order to keep its intended performance. 

LoadFactor Declaration

HashMap can be used by the externally providing initialCapacity and 
loadFactor in its constructor.

But in TreeMap it is not possible to provide any external initial capacity or load factor.

0 comments:

Post a Comment

 
Copyright © 2019 techfloaters • All Rights Reserved.
Template Design by Ashok Veer ( veersoft solution)