WikiGalaxy

Personalize

Java HashSet - Introduction

What is a HashSet?

A HashSet in Java is a collection that uses a hash table for storing elements. It does not allow duplicate elements and provides constant time performance for basic operations like add, remove, and contains, assuming the hash function disperses the elements properly.


import java.util.HashSet;
class HashSetExample {
  public static void main(String[] args) {
    HashSet set = new HashSet();
    set.add("Apple");
    set.add("Banana");
    set.add("Orange");
    System.out.println(set);
  }
}
    

Key Characteristics:

HashSet is part of the Java Collections Framework and implements the Set interface. It does not guarantee the order of elements and allows null values.

Console Output:

[Apple, Banana, Orange]

Adding Elements to HashSet

Adding Elements

The add() method is used to add elements to the HashSet. If the element is already present, the set will not change, and the method will return false.


import java.util.HashSet;
class HashSetAddExample {
  public static void main(String[] args) {
    HashSet set = new HashSet();
    set.add("Mango");
    set.add("Mango"); // Duplicate
    set.add("Grapes");
    System.out.println(set);
  }
}
    

Handling Duplicates:

HashSet automatically handles duplicates by ignoring them. Therefore, even if you try to add a duplicate element, it won’t be added.

Console Output:

[Mango, Grapes]

Removing Elements from HashSet

Removing Elements

You can remove elements from a HashSet using the remove() method. This method returns true if the element was present and removed, otherwise false.


import java.util.HashSet;
class HashSetRemoveExample {
  public static void main(String[] args) {
    HashSet set = new HashSet();
    set.add("Cherry");
    set.add("Peach");
    set.remove("Cherry");
    System.out.println(set);
  }
}
    

Effect of Removal:

Once an element is removed, it is no longer part of the HashSet, and any further operations on it will not affect the set.

Console Output:

[Peach]

Checking Element Presence in HashSet

Checking for Elements

The contains() method checks whether a specific element is present in the HashSet. It returns true if the element is found, otherwise false.


import java.util.HashSet;
class HashSetContainsExample {
  public static void main(String[] args) {
    HashSet set = new HashSet();
    set.add("Lemon");
    set.add("Lime");
    System.out.println(set.contains("Lemon"));
    System.out.println(set.contains("Orange"));
  }
}
    

Utility of contains() Method:

The contains() method is useful for checking element existence without manually iterating through the HashSet.

Console Output:

true

false

Iterating over HashSet

Iterating Elements

You can iterate over elements in a HashSet using an Iterator or a for-each loop. This allows you to access each element sequentially.


import java.util.HashSet;
import java.util.Iterator;
class HashSetIteratorExample {
  public static void main(String[] args) {
    HashSet set = new HashSet();
    set.add("Kiwi");
    set.add("Pineapple");
    Iterator it = set.iterator();
    while(it.hasNext()) {
      System.out.println(it.next());
    }
  }
}
    

Iterating with Iterator:

Using an iterator is a safe way to iterate over a HashSet, especially when you need to remove elements during iteration.

Console Output:

Kiwi

Pineapple

HashSet Size and Clearing

Size and Clear Methods

The size() method returns the number of elements in the HashSet. The clear() method removes all elements, leaving the set empty.


import java.util.HashSet;
class HashSetSizeClearExample {
  public static void main(String[] args) {
    HashSet set = new HashSet();
    set.add("Strawberry");
    set.add("Blueberry");
    System.out.println("Size: " + set.size());
    set.clear();
    System.out.println("Size after clear: " + set.size());
  }
}
    

Utility of Size and Clear:

These methods are essential for managing the HashSet's lifecycle, such as resetting it or checking its capacity before operations.

Console Output:

Size: 2

Size after clear: 0

HashSet and Null Values

Handling Null Values

HashSet allows null elements. However, adding multiple nulls will still result in only one null value being stored.


import java.util.HashSet;
class HashSetNullExample {
  public static void main(String[] args) {
    HashSet set = new HashSet();
    set.add(null);
    set.add(null);
    System.out.println(set);
  }
}
    

Considerations for Nulls:

While HashSet supports null values, it's crucial to handle them carefully to avoid NullPointerExceptions in operations.

Console Output:

[null]

HashSet Performance

Performance Considerations

HashSet provides constant time performance for basic operations like add, remove, and contains, provided the hash function disperses elements properly across the buckets.


import java.util.HashSet;
class HashSetPerformanceExample {
  public static void main(String[] args) {
    HashSet set = new HashSet();
    for (int i = 0; i < 1000000; i++) {
      set.add(i);
    }
    System.out.println("Added 1,000,000 elements.");
  }
}
    

Scalability:

HashSet is suitable for large datasets where quick insertion, deletion, and lookup are required, making it ideal for caching and indexing applications.

Console Output:

Added 1,000,000 elements.

HashSet vs. TreeSet

Comparison with TreeSet

While HashSet is based on a hash table, TreeSet is based on a tree structure. HashSet offers constant time performance, whereas TreeSet guarantees log(n) time complexity for basic operations and maintains elements in sorted order.


import java.util.HashSet;
import java.util.TreeSet;
class SetComparisonExample {
  public static void main(String[] args) {
    HashSet hashSet = new HashSet();
    TreeSet treeSet = new TreeSet();
    hashSet.add("Banana");
    hashSet.add("Apple");
    treeSet.add("Banana");
    treeSet.add("Apple");
    System.out.println("HashSet: " + hashSet);
    System.out.println("TreeSet: " + treeSet);
  }
}
    

Use Cases:

Choose HashSet for performance-critical applications where order does not matter, and TreeSet when sorted order is required.

Console Output:

HashSet: [Banana, Apple]

TreeSet: [Apple, Banana]

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025