Set Interface - Notes By ShariqSP
Set Interface in Java
The Set
interface in Java represents a collection of unique elements, i.e., it does not allow duplicate elements. It does not maintain the insertion order of elements.
Methods:
- add(E element): Adds the specified element to the set if it is not already present.
- remove(Object obj): Removes the specified element from the set if it is present.
- contains(Object obj): Returns true if the set contains the specified element.
- isEmpty(): Returns true if the set contains no elements.
- size(): Returns the number of elements in the set.
- clear(): Removes all elements from the set.
Implementation Classes:
The Set
interface has several implementation classes in Java:
- HashSet: Hash table-based implementation of the
Set
interface. - LinkedHashSet: Hash table and linked list implementation of the
Set
interface, with predictable iteration order. - TreeSet: Red-Black tree implementation of the
Set
interface, sorted according to the natural ordering of its elements or by a custom comparator.