Difference between HashMap and HashSet in Java
In this post, we’ll see the difference between HashMap and HashSet, which are two of the most commonly used classes in Java Collections Framework.
One of the most common and useful data structures in Java is the hash table, which is a data structure that maps keys to values using a hash function. A hash table allows fast and easy insertion, retrieval, and deletion of key-value pairs. Two of the most widely used types of hash tables in Java are HashMap and HashSet, which implement the Map and Set interfaces respectively. However, HashMap and HashSet have some significant differences and trade-offs that make them suitable for different use cases.
1. Overview of HashMap in Java
HashMap is a class that implements the Map interface and uses a hash table as its underlying data structure to store key-value pairs. A key is an object that identifies a value, and a value is an object that contains some data. In HashMap, each key must be unique; however, duplicate values are allowed. The keys and values can be of any type, such as String, Integer, etc. It offers many benefits over other types of maps.
HashMapallows fast access to elements by using the hash code of the keys. It uses an array of buckets to store the key-value pairs. Each bucket has a unique index calculated by applying a hash function to the key. When we insert or retrieve an element from theHashMap, we use the key to calculate the hash code and find the index of the bucket where the element is stored.HashMapdoes not maintain any order of the elements in the map. This means that the elements in aHashMapare stored in a random order according to their hash codes.HashMapallows null keys and null values in the map. This means that we can insert, retrieve, or remove null values from aHashMapwithout any problem.HashMapprovides additional methods to manipulate the map, such as put, get, remove, containsKey, containsValue, size, clear, etc. These methods allow us to add, update, delete, or check elements in the map.
Here is an example of how to create and use a HashMap in Java:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import java.util.HashMap; import java.util.Map; class Main { public static void main(String[] args) { // Create a HashMap object Map<String, Integer> map = new HashMap<>(); // Add some key-value pairs to the map map.put("Aaron", 10); map.put("Bella", 20); map.put("Casey", 30); // Print the map System.out.println("HashMap: " + map); // {Aaron=10 ,Bella=20 ,Casey=30} // Get the value associated with a key System.out.println("Value for Bella: " + map.get("Bella")); // 20 // Remove a key-value pair from the map map.remove("Aaron"); // Print the updated map System.out.println("HashMap: " + map); // {Bella=20 ,Casey=30} // Check if a key exists in the map System.out.println("Contains Bella: " + map.containsKey("Bella")); // true // Check if a value exists in the map System.out.println("Contains 10: " + map.containsValue(10)); // false } } |
2. Overview of HashSet in Java
HashSet is a class that implements the Set interface and uses a hash table as its underlying data structure to store elements. A set is an unordered collection of elements that does not allow duplicates. The elements in a set can be of any type, such as String, Integer, etc. It offers some benefits over other types of sets.
HashSetallows fast access to elements by using the hash code of the elements. It uses an array of buckets to store the elements. Each bucket has a unique index calculated by applying a hash function to the element. When we insert or retrieve an element from theHashSet, we use the element to calculate the hash code and find the index of the bucket where the element is stored.HashSetdoes not maintain any order of the elements in the set. This means that the elements in aHashSetare stored in a random order according to their hash codes.HashSetdoes not allow duplicate elements in the set.HashSetallows null elements in the set. This means that we can insert, retrieve, or remove null values from aHashSetwithout any problem.HashSetprovides additional methods to manipulate the set, such as add, remove, contains, size, clear, etc. These methods allow us to add, delete, or check elements in the set.
Here is an example of how to create and use a HashSet in Java:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import java.util.HashSet; import java.util.Set; class Main { public static void main(String[] args) { // Create a HashSet object Set<String> set = new HashSet<>(); // Add some elements to the set set.add("Aaron"); set.add("Bella"); set.add("Casey"); // Print the set System.out.println("HashSet: " + set); // [Bella, Aaron, Casey] // Try to add a duplicate element to the set set.add("Aaron"); // Print the set System.out.println("HashSet: " + set); // [Bella, Aaron, Casey] // Remove an element from the set set.remove("Bella"); // Print the updated set System.out.println("HashSet: " + set); // [Aaron, Casey] // Check if an element exists in the set System.out.println("Contains Aaron: " + set.contains("Aaron")); // true // Check if a null element exists in the set System.out.println("Contains null: " + set.contains(null)); // false } } |
3. Difference between HashMap and HashSet in Java
The functionality of HashMap and HashSet are similar. They both use hashing to store and retrieve elements quickly. However, they also have some differences and trade-offs that we must understand:
- A
HashMapis an implementation ofMapinterface, whereasHashSetis an implementation ofSetinterface. - A
HashMapclass maps a key to a value, whereasHashSetclass stores a unique set of elements. Both follows the contract of their respective interfaces. HashMapdoesn’t permit duplicate keys but allows duplicate values, whereasHashSetallows only distinct elements.HashMapis implemented using a hash table, whereasHashSetis backed by a hash table, which is nothing but aHashMapinstance.HashMapallows null as a key and value in the map, whereasHashSetallows at most one null element.
4. What to use and when?
As we have seen, HashMap and HashSet are both useful data structures in Java that use hashing to store and retrieve elements quickly. Here are some general recommendations on how to choose between them:
- If you need a data structure that can store key-value pairs where each key is unique and can be used to access its associated value, we should use
HashMap. This data structure is ideal for implementing dictionaries, caches, lookups, etc. - If you need a data structure that can store a collection of unique values without any associated keys or values, we should use
HashSet. This data structure is ideal for implementing sets, filters, etc. - If you need a data structure that can store key-value pairs where each key is unique but also maintain the order of the elements according to their natural ordering or by a provided
Comparator, we should use TreeMap instead. This data structure is ideal for implementing sorted maps, ranges, intervals, etc.
That’s all about the differences between HashMap and HashSet in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)