HashSet VS TreeSet

Differences between HashSet and TreeSet


Both HashSet and TreeSet are variants of Set. One is based on Hashing and the other is based on Tree data structure.
Main differences between a HashSet and TreeSet are:
I. Ordering: In a HashSet elements are stored in a random order. In a TreeSet, elements are stored according to natural ordering.
II. Null Value Element: We can store null value object in a HashSet. A TreeSet does not allow to add a null value object.
III. Performance: HashSet performs basic operations like add(), remove(), contains(), size() etc. in a constant size time. A TreeSet performs these operations at the order of log(n) time.
IV. Speed: A HashSet is better than a TreeSet in performance for most of operations like add(), remove(), contains(), size() etc. .
V. Internal Structure: Hashset is internally backed by HashMap but A Treeset backed by a NavigableMap internally.
VI. Features: A TreeSet has more features compared to a HashSet. It has methods like pollFirst(), pollLast(), first(), last(), ceiling(), lower() etc.
VII. Element Comparison: A HashSet uses equals() method for comparison. A TreeSet uses compareTo() method for comparison to maintain ordering of elements.

In most cases hashset is prefered for searching while Treeset is prefered when we need searching with ordering.

0 comments:

Post a Comment

My Instagram