Java – Set interface with example

In this article, we will discuss Set interface in detail

1. Key points about Set:

  • Set doesn’t allow duplicate items
  • also doesn’t maintain insertion-order

2. Set interface:

  • Set is a sub-interface of Collection interface (i.e.; Set extends Collection)
  • To represent a group of element/objects as a single unit/entity, where duplicates aren’t allowed
  • Set allows only unique element/objects to be inserted
  • Set doesn’t maintain insertion-order
  • While iterating through Set, we will get items in random-order (as against insertion-order in List)
  • There are 2 direct concrete classes for Set interface viz.; HashSet, LinkedHashSet and another one TreeSet (through SortedSet –> NavigableSet)
  • Set interface doesn’t contain any methods but only inherited methods from Collection interface
  • Present in java.util package and extends java.util.Collection interface
14-Set-interace-in-java

Source: Team BenchResources.Net

3. Below listed classes implements Set interface

  • HashSet
  • LinkedHashSet
  • TreeSet (through SoretdSet –> NavigableSet)

4. Factors to consider while discussing any collection class

We should consider below factors while discussing any implementation class of collection framework or for that matter Map interface,

  • Underlying data structure
  • Duplicates are allowed or Not
  • Insertion order is maintained or Not
  • Whether NULL insertion is possible or Not
  • If possible, how many NULL values can be inserted
  • Whether collection class provide sorting, by default
  • Is there any way to apply customized sorting
  • Performance, while dealing with retrieval or manipulation (addition/deletion)
  • By default, all methods are synchronized or Not

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - HashSet class with examples
Java - Enumeration v/s Iterator v/s ListIterator interfaces