We have seen List in java, but if we want to save data in which duplicates are not allowed then we can use Set in Java.
Set in Java is an interface available in java.util package which extends a Collection interface. Set in java is an unordered collection or list of objects where duplicates are not allowed. SortedSet and NavigableSet are child interfaces of the Set interface.
Following is Hierarchy for the set in java.
SortedSet:
SortedSet is a child interface of the Set interface in java.
The elements of SortedSet are ordered either by using a natural sorting order or by using a Comparator. All the elements which are inserted into a sorted set must implement the Comparable interface.
Insertion order is not preserved in SortedSet since the order is based on comparator or natural sorting order.
NavigavleSet:
This is a child interface of SortedSet. Hence NavigableSet is the same as SortedSet but with an additional set of navigation methods available are available in the NavigableSet interface.
HashSet:
HashSet is the child class of the Set Interface. Which uses a hashtable for the storage. Insertion order is not preserved in HashSet.
LinkedHashSet:
LinkedHashSet is a child class of the Set interface that also extends HashSet. Insertion order is maintained in LinkedHashSet.
TreeSet:
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements the NavigableSet interface. Insertion order is not preserved in java TreeSet.
ConcurrentSkipListSet:
The ConcurrentSkipListSet class implements the NavigableSet and the AbstractSet class. It provides a scalable and concurrent version of NavigableSet in Java. The implementation of ConcurrentSkipListSet is based on ConcurrentSkipListMap. The elements in ConcurrentSkipListSet are sorted by default in their natural ordering or by a Comparator provided the time of object creation. This set is thread-safe.
EnumSet:
An EnumSet is a specialized Set collection to work with enum classes. It implements the Set interface and extends from AbstractSet. It contains only enum values and all the values have to belong to the same enum.
CopyOnWriteArraySet:
CopyOnWriteArraySet extends AbstractSet.
When we try to add or remove any data from the set while iterating over the set, we will get ConcurrentModificationException. CopyOnWriteArraySet is thread-safe and we can add or remove objects while iterating over the set.
All the details about each set and examples for the same we will see in detail one by one.
Let’s see the difference between List and Set.
List | Set |
Insertion order is preserved inside the List. | Insertion order is not preserved in Set. |
Duplicate elements are allowed in the List. | Duplicate elements are not allowed in Set. |
Null can be stored multiple times. | Null is allowed only once. |