In Java, HashSet is the other data structure. It is implemented by using a hash table. It is used to store unique elements. HashMap is used in HashSet to store its elements internally. By using the add() method, elements are added to HashSet. It takes an element as a parameter. Then the element is hashed and stored in HashMap as a key with some value. Let’s have a look at Implementation of HashSet code:Code
3.3.
java
4.
Difference between HashMap and HashSet
5.
Frequently Asked Questions
5.1.
What is the difference between HashMap and Hashtable and HashSet?
5.2.
Why Hashtable is faster than HashMap?
5.3.
What is the difference between Hashtable and ConcurrentHashMap?
Java HashMap is a Map that uses a hash table for storage, while HashSet is a Set that also employs a hash table for storage.
In this blog, we will learn about HashMap and HashSet Features, Implementation, and their differences. Now let’s go ahead in the blog and learn more interesting differences between HashMap and HashSet.
In Java, HashMap is commonly used. It is useful in a wide range of applications, such as caching systems, database operations, and more. HashMap is a class. It is used to store and retrieve key-value pairs. It is a part of the Java Collections Framework. It also provides a flexible and efficient way to map keys to their corresponding values. In a HashMap, keys are unique and are used to retrieve their associated values. The values can be of any data type, such as strings, integers, or custom objects. HashMap uses a hash function to map keys to their corresponding values, allowing fast retrieval times.
Features of HashMap
Some of the features of HashMap in Java are given below:
Iterability: HashMap can be iterated over using iterators, which allow for easy traversal of the key-value pairs stored in the HashMap.
Null Values: HashMap allows null values to be stored as keys or values.
Fast Lookup: HashMap uses a hash function to map keys to their corresponding values, which allows for fast lookup times. The time complexity on average for operations like put(), get(), and remove() is O(1).
Resizable: HashMap can resize dynamically based on the number of elements it contains.
Not Thread-safe: HashMap is not thread-safe. It also requires synchronization if used in a multi-threaded environment. In such cases, ConcurrentHashMap can be used instead.
Implementation of a HashMap
In Java, HashMap is a data structure. It allows us to store and retrieve key-values. It is an array of buckets for implementation. Here each bucket is a linked list of entries. Each entry in the linked list stores a key-value pair and a next entry in the list. The key is first hashed to generate an index in the bucket array then stored in HashMap. Then the key value pair is added to the linked list. To retrieve a value, the linked list is searched for an entry with the same key. Let’s have a look at Implementation of HashMap code:
Code
java
java
import java.util.*;
public class HashMapCode { static class HashMap<K,V> { private class Node { K key; V value; public Node(K key, V value) { this.key = key; this.value = value; } } private int n; private int N; private LinkedList<Node> buckets[]; public HashMap() { this.N = 4; this.buckets = new LinkedList[4]; for(int i=0; i<4; i++) { this.buckets[i] = new LinkedList<>(); } } private int hashFunction(K key) { int bi = key.hashCode(); return Math.abs(bi) % N; } private int searchInLL(K key, int bi) { LinkedList<Node> ll = buckets[bi]; for(int i=0; i<ll.size(); i++) { if(ll.get(i).key == key) { return i; } } return -1; } private void rehash() { LinkedList<Node> oldBucket[] = buckets; buckets = new LinkedList[N*2]; for(int i=0; i<N*2; i++) { buckets[i] = new LinkedList<>(); } for(int i=0; i<oldBucket.length; i++) { LinkedList<Node> ll = oldBucket[i]; for(int j=0; j<ll.size(); j++) { Node node = ll.get(j); put(node.key, node.value); } } } public void put(K key, V value) { int bi = hashFunction(key); int di = searchInLL(key, bi); if(di == -1) { buckets[bi].add(new Node(key, value)); n++; } else { Node node = buckets[bi].get(di); node.value = value; } double lambda = (double)n/N; if(lambda > 2.0) { rehash(); } } public boolean containsKey(K key) { int bi = hashFunction(key); int di = searchInLL(key, bi); if(di == -1) { return false; } else { return true; } } public V remove(K key) { int bi = hashFunction(key); int di = searchInLL(key, bi); if(di == -1) { return null; } else { Node node = buckets[bi].remove(di); n--; return node.value; } } public V get(K key) { int bi = hashFunction(key); int di = searchInLL(key, bi); if(di == -1) { return null; } else { Node node = buckets[bi].get(di); return node.value; } } public ArrayList<K> keySet() { ArrayList<K> keys = new ArrayList<>(); for(int i=0; i<buckets.length; i++) { LinkedList<Node> ll = buckets[i]; for(int j=0; j<ll.size(); j++) { Node node = ll.get(j); keys.add(node.key); } } return keys; } public boolean isEmpty() { return n == 0; } }
In Java, HashSet is a commonly used data structure. It is useful in a wide range of applications, such as checking for duplicates, filtering data, and more. HashSet is a class. It is used to store a collection of unique elements. It is a part of the Java Collections Framework and provides an efficient way to store and manipulate a group of elements without duplicates. In a HashSet, elements are unique and unordered, and the order in which they are stored may vary. The elements can be of any data type, such as strings, integers, or custom objects. HashSet uses a hash function to map elements to their corresponding buckets, which allows for fast lookup times.
Features of HashSet
Some of the key features of HashSet in Java:
Stores Unique Elements: HashSet is used to store a collection of unique elements.
Iterability: HashSet can be iterated over using iterators.
Allows Null Values: HashSet allows null values to be stored as elements.
Not Thread-safe: HashSet is not thread-safe and requires synchronization if used in a multi-threaded environment. In such cases, Concurrent HashSet can be used instead.
Fast Lookup: HashSet uses a hash function to map elements to their corresponding buckets, which allows for fast lookup times. On average, the time complexity for operations like add(), contains(), and remove() is O(1).
Resizable: HashSet can resize dynamically based on the number of elements it contains, which allows for efficient use of memory.
Ordering: HashSet does not maintain any order of the elements stored in it. However, LinkedHashSet can be used instead if order needs to be maintained.
Implementation of HashSet
In Java, HashSet is the other data structure. It is implemented by using a hash table. It is used to store unique elements. HashMap is used in HashSet to store its elements internally. By using the add() method, elements are added to HashSet. It takes an element as a parameter. Then the element is hashed and stored in HashMap as a key with some value. Let’s have a look at Implementation of HashSet code:
public class Hashing { public static void main(String args[]) { HashSet<Integer> set = new HashSet<>(); set.add(1); set.add(2); set.add(3); set.add(4); System.out.println("size of set is : " + set.size()); if(set.contains(2)) { System.out.println("2 is present "); } if(!set.contains(7)) { System.out.println("7 is not present"); } set.remove(1); if(!set.contains(1)) { System.out.println("1 is not present"); } System.out.println(set); set.add(0); Iterator it = set.iterator(); while (it.hasNext()) { System.out.print(it.next() + ", "); } System.out.println(); if(!set.isEmpty()) { System.out.println("set is not empty"); } } }
You can also try this code with Online Java Compiler
What is the difference between HashMap and Hashtable and HashSet?
HashMap and Hashtable store key-value pairs, with HashMap allowing nulls and being non-synchronized, while Hashtable is synchronized and doesn’t allow nulls. HashSet only stores unique elements without key-value pairs, internally using a HashMap.
Why Hashtable is faster than HashMap?
Actually, HashMap is generally faster than Hashtable because HashMap is unsynchronized, allowing multiple threads to access it concurrently. Hashtable is synchronized, which introduces overhead, making it slower in multi-threaded environments.
What is the difference between Hashtable and ConcurrentHashMap?
Hashtable is fully synchronized, locking the entire table on updates, while ConcurrentHashMap allows concurrent read and write operations by locking only portions of the map, making it more efficient in multi-threaded environments.
Conclusion
We hope this article helped you understand the difference between HashMap and HashSet. We have also discussed the Introduction, features and implementation of HashMap and HashSet. Do read below articles to enhance your knowledge.