Key Characteristics of a Set:
No Duplicates: A Set does not allow duplicate elements. If you try to add a duplicate element, the set will not include it, and the add operation will return false.
Unordered Collection: Unlike List, a Set does not maintain any particular order of elements. The elements may appear in a different order than they were inserted.
Null Elements: Set can contain at most one null element (if the implementation allows null).
Common Set Implementations:
Java provides several classes that implement the Set interface:
HashSet:
Uses a hash table to store the elements.
Does not maintain any order of elements.
Provides constant time performance for basic operations like add, remove, and contains.
LinkedHashSet:
Extends HashSet and maintains the order of elements based on their insertion order.
Useful when you need a set that preserves insertion order
TreeSet:
Implements the NavigableSet interface and stores elements in a sorted order, determined by their natural ordering or a provided Comparator.
Slower than HashSet but provides order-related operations like first(), last(), headSet(), etc.
Common Operations on a Set:
Add an Element: boolean add(E e)
Adds the specified element to the set if it is not already present. Returns true if the element was added, and false if it was already in the set.
Remove an Element: boolean remove(Object o)
Removes the specified element from the set if it is present. Returns true if the element was removed, and false if it was not present.
Check if an Element Exists: boolean contains(Object o)
Returns true if the set contains the specified element.
Get the Size of the Set: int size()
Returns the number of elements in the set.
Iterate through the Set:
You can iterate through a set using an enhanced for-loop or an iterator