Java Intermediate

0% completed

Previous
Next
Basics of HashSet Class

The HashSet class is a concrete implementation of the Set interface in Java and is part of the java.util package. It is designed to store a collection of unique elements, meaning that duplicates are not allowed. Internally, HashSet uses a hash table to store elements, which provides constant-time performance for basic operations like add, remove, and contains—assuming the hash function disperses elements properly.

Syntax

To create a HashSet, you use the following syntax:

HashSet<Type> set = new HashSet<Type>();
  • Explanation:
    • HashSet<Type> declares a HashSet that will store objects of the specified Type.
    • The constructor new HashSet<Type>() initializes an empty HashSet that grows dynamically as elements are added.

Additional constructors allow you to specify the initial capacity and the load factor:

HashSet<Type> set = new HashSet<Type>(initialCapacity); HashSet<Type> set = new HashSet<Type>(initialCapacity, loadFactor);
  • Explanation:
    • Initial Capacity: Determines the number of buckets initially allocated.
    • Load Factor: A measure that decides when to increase the capacity (e.g., 0.75 means the capacity will be doubled when 75% full).

Key Characteristics

  • Unordered Collection: HashSet does not maintain any order of its elements. The elements are stored based on their hash codes, so the order may appear random.
  • Efficient Performance: Because it uses a hash table internally, operations such as add, remove, and contains typically run in constant time, O(1), on average.
  • Null Elements: A HashSet permits the inclusion of a single null element.
  • Not Synchronized: Unlike some legacy classes, HashSet is not synchronized by default. If thread safety is required, you must handle synchronization externally.

Example

Below is a simple example demonstrating the creation and basic operations of a HashSet.

Java
Java

. . . .

Example Explanation:

  • Creation:
    • A HashSet<String> called colors is created to store unique color names.
  • Adding Elements:
    • The add() method inserts elements; attempting to add a duplicate (e.g., "Red") does not change the set.
  • Element Check:
    • The contains() method is used to verify that "Blue" exists in the set.
  • Final Output:
    • The HashSet is printed, showing only unique elements, and its size is displayed.

The HashSet class is an efficient and flexible implementation of the Set interface that guarantees uniqueness by using a hash table. It supports all standard set operations such as adding, removing, checking for elements, and iterating over the collection. Understanding how to use HashSet is essential for scenarios where duplicate entries are not allowed and performance is a critical factor.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next