Java HashSet Class
The HashSet class belongs to the java.util package where it serves as an implementation of the Set interface. The HashSet stores only unique items by using a hash table which provides constant-time performance for fundamental operations including add, remove, and contains (average case).
Key Features
- Stores unique elements only
- Unordered: does not guarantee the order of elements
- Allows null elements (only one null allowed)
- No indexing: can't access elements by position
- Not synchronized
Syntax
HashSet set = new HashSet<>();
Methods
Adding Elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Banana");
Example
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet colors = new HashSet<>();
// Add elements
colors.add("Red");
colors.add("Green");
colors.add("Blue");
colors.add("Green"); // Duplicate
// Display the set
System.out.println("HashSet: " + colors);
// Check existence
if (colors.contains("Blue")) {
System.out.println("Blue is in the set.");
}
// Remove an item
colors.remove("Red");
// Print after removal
System.out.println("Updated HashSet: " + colors);
// Clear the set
colors.clear();
// Check if empty
System.out.println("Is the set empty? " + colors.isEmpty());
}
}
Note
- If you need to store items without duplicates and order doesn't matter then HashSet is the appropriate choice.
- To maintain element order you should choose LinkedHashSet or TreeSet over this structure.
- This implementation lacks thread safety but offers Collections.synchronizedSet() and CopyOnWriteArraySet as concurrent alternatives.
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com