Set Interface extends the Collection interface. It represents the unordered set of elements. However, the set doesn’t allow us to store duplicate items. In addition, it can store at most one null value. Set is implemented by HashSet, LinkedHashSet, and TreeSet.
Syntax
Set s1 = new HashSet();
Set s2 = new LinkedHashSet();
Set s3 = new TreeSet();
- HashSet
- HashSet class implements Set Interface.
- In other words, it represents a collection that uses a hash table for storage.
- It contains unique items.
- Eg –
- HashSet set=new HashSet();
- set.add(“Ram”);
- LinkedHashSet
- LinkedHashSet extends the HashSet class and implements the Set interface.
- It also contains unique elements.
- It permits null elements and maintains the insertion order of elements.
- Eg –
- LinkedHashSet set=new LinkedHashSet();
- set.add(“Ram”);
- SortedSet
- SortedSet is the alternate of the Set interface.
- It represents an ordered list of elements.
- The elements of the SortedSet are arranged in the increasing (ascending) order.
- Eg –
- SortedSet set = new TreeSet();
- set.add(“Ram”);
- TreeSet
- TreeSet class implements the Set interface.
- It contains unique elements.
- It has quite fast access and retrieval time.
- The elements in TreeSet stored in ascending order.
- Eg –
- TreeSet set=new TreeSet();
- set.add(“Ram”);