Set Interface

The Set interface is a part of the Java Collections Framework and is a subinterface of Collection. It represents a collection that does not allow duplicate elements. The Set interface does not provide any additional methods beyond those specified in the Collection interface, but it adds the stipulation that duplicates are not allowed.

Key Characteristics of Set

  1. No Duplicates: A Set does not allow duplicate elements. Each element in a Set must be unique.
  2. Unordered Collection: The Set interface does not guarantee the order of elements. The insertion order is not preserved.
  3. Single Null Element: A Set can contain at most one null element.
  4. Implements Collection: The Set interface inherits all the methods from the Collection interface.

Common Implementations of Set

  1. HashSet: Stores elements in a hash table. It does not guarantee any order of elements.
  2. LinkedHashSet: Stores elements in a hash table with a linked list running through it, which maintains the insertion order.
  3. TreeSet: Stores elements in a red-black tree, which sorts the elements based on their natural order or a specified comparator.
Code Example
Output
Set: [Apple, Cherry, Banana]
Contains 'Apple': true
After removing 'Banana': [Apple, Cherry]
Iterating over set:
Apple
Cherry
Size of set: 2
Is set empty after clear: true