What is Hash Table?
A hash table is a data structure that organizes data using hash functions, enabling fast insertion and search operations.
There are two main types of hash tables: Hash Set and Hash Map.
A hash set is a type of set data structure that ensures all stored values are unique. A hash map is a type of map data structure that stores data in key-value pairs.
Insertion and search are fundamental operations in a hash table.
Additionally, other operations, such as deletion, are built upon these two. For instance, to remove an element, the hash table first searches for its location and then deletes it if it is found. Let's take a look at Hash Set first.
What is Hash Map?
The Hash Map is one of the implementations of a map which is used to store (key, value) pairs. The code below is the implementation of Hash Map in Java.

One common use case for a hash map is when we need to store additional information beyond just the key. In such cases, a hash map allows us to establish a mapping between a key and its associated data.
What is Hash Set?
The Hash Set is one of the implementations of a set data structure backed by Hash Map to store no repeated values. It uses the keys of a HashMap to store elements, while the values are set to a fixed dummy object. The down below is the example of Hash Set in Java.

As we know, inserting a new value and checking if a value exists in a hash set are both simple and efficient operations. For this reason, a hash set is commonly used to determine whether a value has already appeared or not.
Understanding Time Complexity
When working with collections in Java, understanding the time complexity of built-in functions is essential for writing efficient code. In this chapter, we will cover the time complexity of Hash Map and Hash Set, and explain the reasoning behind these complexities.
1. Hash Map Time Complexity

2. Hash Set Time Complexity

Both HashSet and HashMap provide constant-time performance O(1) in the average case since they both uses Hash Table. To understand that, we should go over Hash Table Mechanism.
- A hash table uses a hash function to compute an index (or bucket) where an element should be stored or retrieved.
- When you insert or search for an element, the hash function calculates the index in constant time O(1), assuming the hash function is well-distributed.
- This allows direct access to the bucket where the element is stored, avoiding the need to traverse the entire collection.
In the worst-case scenario, where hash collisions occur frequently (e.g., all elements hash to the same bucket), the time complexity of operations degrades to O(n), where n is the number of elements. However, this is rare with a good hash function and proper resizing of the hash table.