Set in Java

Beknazar
3 min readMar 30, 2022

--

We will take a look into java.util.Set in this article. The Set is part of the collections framework in Java. It is an interface and it has three main concrete classes. Set doesn’t allow duplicates.

HashSet

It implements the Set interface. Internally, it’s based on HashMap. It doesn’t maintain insertion order and it doesn’t guarantee that the order will remain constant over time. It allows null value. HashSet is not synchronized. It offers constant time performance for the basic operations such as add, remove, contains, and size.

LinkedHashSet

This class extends the HashSet class and implements the Set interface. It maintains a doubly-linked list in addition to HashMap(hash table). The linked list defines the insertion order. So the main difference between LinkedHashSet and HashSet is that LinkedHashSet maintains the insertion(iteration) order. It allows null value. HashSet is not synchronized. It offers constant time performance for the basic operations such as add, remove, contains, and size.

TreeSet

A NavigableSet implementation based on a TreeMap. The elements are sorted using their natural ordering, or by a Comparator provided at a set creation time. It is not synchronized.

Let’s see one more example with our own sorting order.

In both examples, I didn’t create from the Set reference type but with TreeSet because otherwise, it loses it is NavigableSet methods.

--

--