Difference and similarities between HashSet, LinkedHashSet, and TreeSet in Java

Introduction

We all have been using HashSet, LinkedHashSet, and TreeSet in Java. But do you know what are the differences between them and how they all are similar too in some ways?

To gain more knowledge about these data structures, let’s discuss their differences and similarities below.

Differences:

Discussion PointHashSetLinkedHashSetTreeSet
Data Structure used
internally
Uses HashMap Uses LinkedHashMapUses TreeMap
Order if elementsDoesn’t maintain the order
of insertion and stores
unique elements
Maintains insertion order
of elements
Stores elements in sorted
order
(ascending by default),
which can be defined using
a custom comparator.
Time complexity of
operations
Takes O(1) for insertion,
updating, and deletion
Takes O(1) for insertion,
updating, and deletion
Takes O(log(n)) for
insertion, updating and
deletion
Null value handlingAllows only one null valueAllows only one null valueDoesn’t allow null value.
Will throw
NullPointerException upon
insertion of null value.
How to use (syntax)HashSet a = new
HashSet();
LinkedHashSet a = new
LinkedHashSet();
TreeSet a = new TreeSet();
PerformanceHas better performance
when compared to
LinkedHashSet and
TreeSet.
Performs slower than
TreeSet. And almost similar
to HashSet but slower
because it internally
maintains LinkedList to
maintain the insertion
order of elements.
Performs better than
LinkedHashSet except for
insertion and removal
operations because it has
to sort the elements after
each insertion and removal
operation.

Similarities:

  • HashSet, LinkedHashSet, and TreeSet all are designed to store unique elements i.e, they can’t store duplicate elements even if duplicates are inserted into them.
  • These three are clonable and serializable.
  • To use them in a multi-threading environment we need to make them externally synchronized as both LinkedHashSet and TreeSet are not thread-safe.

I hope now you understand the difference and similarities between HashSet, LinkedHashSet, and TreeSet in Java. These things are necessary to be kept in mind while using them. To practice more problems you can check out MYCODE | Competitive Programming.

Leave a Reply

Your email address will not be published. Required fields are marked *