HashSet
HashSet is the most commonly used implementation of the Set interface. It stores unique elements and does not guarantee any particular order when you iterate through them.
1. What is HashSet?
HashSet is the most commonly used implementation of the Set interface. It stores unique elements and does not guarantee any particular order when you iterate through them.
2. Why is it used?
HashSet is used when you need fast operations (adding, removing, checking existence) and don't care about maintaining any specific order of elements.
3. Real-Life Example
Think of tossing unique tokens into a large basket without arranging them in any particular order. You can still quickly check if a specific token is in the basket, even though there's no defined sequence.
4. Syntax
javaHashSet<DataType> setName = new HashSet<>();
5. Example Program
javaimport java.util.HashSet; public class HashSetDemo { public static void main(String[] args) { HashSet<Integer> numbers = new HashSet<>(); numbers.add(10); numbers.add(20); numbers.add(10); // duplicate, ignored System.out.println(numbers.size()); } }
Output:
26. Key Points to Remember
HashSetoffers very fast add, remove, and search operations on average.- The iteration order of a
HashSetis unpredictable and should never be relied upon. HashSetinternally uses aHashMapto store its elements.