A Set is a collection in Java that does not allow duplicate elements. It is part of the java.util package and extends the Collection interface. Unlike other collections like List, which allows duplicates, a Set ensures that each element is unique.
Sets are great for use cases:
- To ensure that a collection has no duplicate entries.
- When the order of elements does not matter or when you need elements sorted in a specific order.
- When performing operations like union, intersection, and difference on sets.
Features
- No Duplicates: Sets automatically reject duplicate elements.
- Unordered: The elements in a Set are not stored in a particular order. If you need ordered elements, you can look into specific implementations (like
TreeSet
orLinkedHashSet
). - Dynamic Size: The size of a Set can grow or shrink dynamically as elements are added or removed.
- Null Elements: Most Set implementations allow one null element, but this can vary depending on the specific Set implementation.
Common Implementations of Set
- HashSet: It is the most commonly used implementation of the Set interface. It is backed by a hash table and offers constant time performance for basic operations (like add, remove, contains). Does not guarantee any order of elements.
- LinkedHashSet: This implementation maintains the insertion order. It combines the features of a HashSet and a LinkedList, making it a good choice when the order of elements matters.
- TreeSet: A TreeSet is a NavigableSet that stores elements in a sorted order. It is backed by a TreeMap and guarantees the order of elements based on their natural ordering or a comparator provided at the time of creation.
Basic Operations on a Set
- add(E e): Adds the specified element to the set if it is not already present.
- remove(Object o): Removes the specified element from the set.
- contains(Object o): Returns true if the set contains the specified element.
- size(): Returns the number of elements in the set.
- isEmpty(): Returns true if the set contains no elements.
- clear(): Removes all elements from the set.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.HashSet; public class SetExample { public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add("Java"); set.add("Python"); set.add("Java"); // Duplicate, won't be added System.out.println(set); // Output: [Java, Python] } } |