import java.util.HashMap;
class Scratch {
public static void main(String[] args) {
HashMap<String, Integer> frequencyMap = new HashMap<>();
frequencyMap.put("word1", 10);
frequencyMap.put("word2", 20);
frequencyMap.put("word3", 30);
System.out.println("frequencyMap = " + frequencyMap);
frequencyMap.put("word2", 25); (1)
System.out.println("frequencyMap = " + frequencyMap);
}
}
What is difference between HashMap and HashSet
Upasana | May 25, 2019 | 2 min read | 368 views
Both HashMap and HashSet are part of Java Collections Framework.
- HashMap
-
HashMap is essentially a Hash table based implementation of Map interface. It permits null values and null key. Duplicate keys are not allowed in map.
- HashSet
-
This class is an implementation of Set interface, backed by a HashMap instance. Set by definition does not allow duplicate values.
Both these classes require its keys to implement equals
and hashcode
method to work properly.
Difference b/w the two
Here is the summary of difference between the two classes:
HashMap | HHashSet | |
---|---|---|
Implementation |
HashMap implements Map interface |
HashSet implements Set interface |
Duplicates |
HashMap allows duplicate values but no duplicate key |
HashSet does not allow duplicates |
Null Values |
HashMap allows single null key and any number of null values |
HashSet allows single null value |
Insertion method |
|
|
Dummy value |
NA |
HashSet creates a single Dummy value to associate with an Object in the backing map |
Code samples
1 | Storing data with a duplicate key will replace the previous data in map. |
frequencyMap = {word1=10, word3=30, word2=20} frequencyMap = {word1=10, word3=30, word2=25}
import java.util.HashSet;
class Scratch {
public static void main(String[] args) {
HashSet<String> dictionary = new HashSet<>();
dictionary.add("word1");
dictionary.add("word2");
dictionary.add("word3");
System.out.println("dictionary = " + dictionary);
dictionary.add("word2");
System.out.println("dictionary = " + dictionary);
dictionary.add(null);
dictionary.add(null);
System.out.println("dictionary = " + dictionary);
}
}
dictionary = [word1, word3, word2] dictionary = [word1, word3, word2] dictionary = [null, word1, word3, word2]
Top articles in this category:
- Difference between HashMap, LinkedHashMap and TreeMap
- Difference between HashMap and ConcurrentHashMap
- What is difference between Vector and ArrayList, which one shall be preferred
- Discuss internals of a ConcurrentHashmap (CHM) in Java
- What is difference between sleep() and wait() method in Java?
- Can the keys in HashMap be mutable
- Difference between Callable and Runnable Interface