Java HashSet

Introduction

HashSet in Java is a part of the Java Collections Framework and implements the Set interface. It is a collection that uses a hash table for storage. Unlike List, a Set does not allow duplicate elements. HashSet provides a way to store unique elements and allows for fast access and retrieval of data.

Table of Contents

  1. What is HashSet?
  2. Key Points About HashSet
  3. Creating a HashSet and Adding Elements
  4. Accessing Elements in a HashSet
  5. Removing Elements from a HashSet
  6. Iterating Over a HashSet
  7. Searching for Elements in a HashSet
  8. HashSet of User-Defined Objects
  9. Common HashSet Methods
  10. Conclusion

1. What is HashSet?

A HashSet is a collection that contains no duplicate elements. It uses a hash table to store the elements, which allows for fast access, insertion, and deletion operations. HashSet does not maintain any order of the elements.

2. Key Points About HashSet

  • No Duplicates: Does not allow duplicate elements.
  • Null Elements: Allows null elements.
  • Order: Does not maintain any specific order of elements.
  • Hashing: Uses hash table for storage.
  • Performance: Provides constant-time performance for basic operations like add, remove, contains, and size.

3. Creating a HashSet and Adding Elements

To create a HashSet, you can use the HashSet constructor. You can then use methods such as add to add elements to the set.

Example:

In this example, we create a HashSet of strings and add a few elements to it.

import java.util.HashSet;
import java.util.Set;

public class HashSetExample {
    public static void main(String[] args) {
        // Creating a HashSet
        Set<String> fruits = new HashSet<>();

        // Adding elements to the HashSet
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add("Apple"); // Duplicate element

        // Displaying the HashSet
        System.out.println("HashSet: " + fruits);
    }
}

Output:

HashSet: [Apple, Banana, Cherry]

4. Accessing Elements in a HashSet

HashSet class don’t have get() method to access the elements because it does not maintain the order of elements. However, you can check for the presence of an element in a HashSet using the contains method.

Example:

In this example, we demonstrate how to check if an element exists in a HashSet.

import java.util.HashSet;
import java.util.Set;

public class AccessHashSet {
    public static void main(String[] args) {
        // Creating a HashSet
        Set<String> fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // Checking for the presence of an element
        System.out.println("Does the HashSet contain 'Banana'? " + fruits.contains("Banana"));
        System.out.println("Does the HashSet contain 'Mango'? " + fruits.contains("Mango"));
    }
}

Output:

Does the HashSet contain 'Banana'? true
Does the HashSet contain 'Mango'? false

5. Removing Elements from a HashSet

You can remove elements from a HashSet using methods such as remove and clear.

Example:

In this example, we demonstrate how to remove elements from a HashSet.

import java.util.HashSet;
import java.util.Set;

public class RemoveHashSet {
    public static void main(String[] args) {
        // Creating a HashSet
        Set<String> fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // Removing an element
        fruits.remove("Banana");

        // Displaying the HashSet after removal
        System.out.println("HashSet after removal: " + fruits);

        // Clearing the HashSet
        fruits.clear();
        System.out.println("HashSet after clearing: " + fruits);
    }
}

Output:

HashSet after removal: [Apple, Cherry]
HashSet after clearing: []

6. Iterating Over a HashSet

You can iterate over a HashSet using various methods such as a simple for-each loop and iterator.

Example:

In this example, we demonstrate different ways to iterate over a HashSet.

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class IterateHashSet {
    public static void main(String[] args) {
        // Creating a HashSet
        Set<String> fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // Using simple for-each loop
        System.out.println("Using simple for-each loop:");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }

        // Using iterator
        System.out.println("Using iterator:");
        Iterator<String> iterator = fruits.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

Output:

Using simple for-each loop:
Apple
Banana
Cherry
Using iterator:
Apple
Banana
Cherry

7. Searching for Elements in a HashSet

You can search for elements in a HashSet using the contains method.

Example:

In this example, we demonstrate how to check if a HashSet contains a given element.

import java.util.HashSet;
import java.util.Set;

public class SearchHashSet {
    public static void main(String[] args) {
        // Creating a HashSet
        Set<String> fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // Check if the HashSet contains a given element
        System.out.println("Does the HashSet contain 'Banana'? " + fruits.contains("Banana"));
        System.out.println("Does the HashSet contain 'Mango'? " + fruits.contains("Mango"));
    }
}

Output:

Does the HashSet contain 'Banana'? true
Does the HashSet contain 'Mango'? false

8. HashSet of User-Defined Objects

You can use HashSet to store user-defined objects. This involves creating a class for the objects you want to store and ensuring that the equals and hashCode methods are properly overridden.

Example:

In this example, we create a Person class and then create a HashSet to store Person objects.

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age && Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}

public class UserDefinedObjectHashSet {
    public static void main(String[] args) {
        // Creating a HashSet of Person objects
        Set<Person> people = new HashSet<>();
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 25));
        people.add(new Person("Charlie", 35));

        // Displaying the HashSet
        System.out.println("HashSet of Person objects: " + people);
    }
}

Output:

HashSet of Person objects: [Person{name='Alice', age=30}, Person{name='Charlie', age=35}, Person{name='Bob', age=25}]

9. All HashSet Class Methods

10. Conclusion

HashSet is a versatile and efficient collection class in Java that provides a way to store unique elements with fast access and retrieval. It is suitable for applications where the order of elements does not matter, and you need to prevent duplicates. Understanding how to create, manipulate, and iterate over HashSet can help you effectively manage collections of unique objects in your Java applications. With methods for adding, removing, accessing, and searching elements, HashSet offers a comprehensive solution for managing sets of data.

By using HashSet, you can ensure that your collections do not contain duplicates, and you can achieve fast performance for basic operations. When thread safety is not a concern, and you do not need sorted data, HashSet is a good choice for managing sets of elements.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top