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.



Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.