Java Collections: Set Interface

--

Set interface extends Collection interface. It is an unordered collection that does not stores duplicate values.

Java Collection: Queue interface → https://medium.com/java-programming-learnings/java-collections-queue-interface-7502028f1542

Creating objects with Set:

Set<Obj> set = new HashSet<Obj>()

Since it is an interface, we cannot create an object of it. It uses an implementation of the HashSet class.

Classes that implements Set interface:

  1. HashSet: HashSet class implements Set interface. It uses the Hash table data structure for data storage.
HashSet<String> hSet = new HashSet<>();

2. LinkedHashSet: It is an ordered version of HashSet. It implements the Set interface and extends the HashSet class. It uses a Hash table and linked list data structure for data storage.

LinkedHashSet<String> lhSet = new LinkedHashSet<>();

3. Treeset: It implements the SortedSet interface. It uses a Tree data structure for storing the elements. It stores objects in sorted and ascending order. Elements are sorted by keys. It can accept only generic types which can comparable.

TreeSet<String> tSet = new TreeSet<>();                          
  • Difference between HashSet, LinkedHashSet, and TreeSet.

Code Implementation

--

--

Shradha Yewale
Learnings with Java programming by shradha yewale

Software Development Engineer | API Development | Web Development| Java | Spring Boot | React JS