In this post, we will learn the difference between HashSet and HashMap in Java. This is a frequently asked question in Java interviews for beginners. Let's dive into it.
Difference between HashSet and HashMap in Java
Features | HashSet | HashMap |
---|---|---|
Interface | Implements Set interface | Implements Map interface |
Data Storage | Stores data as objects | Stores data as key-value pairs |
Internal Structure | Uses HashMap internally | Uses an array of Entry<K, V> objects internally |
Duplicate Elements | Doesn't allow duplicates | Allows duplicate values but not duplicate keys |
Null Elements | Allows only one null element | Allows one null key and multiple null values |
Insertion Operation | Requires one object | Requires two objects - key and value |
Performance | Slightly slower than HashMap | Slightly faster than HashSet |
Example with HashSet:
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
// Create a HashSet
HashSet<String> hSet = new HashSet<>();
// Add elements
hSet.add("apple");
hSet.add("banana");
hSet.add("cherry");
hSet.add("apple"); // Trying to add a duplicate
// Display the HashSet
System.out.println("HashSet:");
for (String fruit : hSet) {
System.out.println(fruit);
}
}
}
Output:
HashSet:
apple
banana
cherry
Example with HashMap:
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
// Create a HashMap
HashMap<Integer, String> hMap = new HashMap<>();
// Add elements (key-value pairs)
hMap.put(1, "apple");
hMap.put(2, "banana");
hMap.put(3, "cherry");
hMap.put(3, "date"); // Trying to use a duplicate key
// Display the HashMap
System.out.println("HashMap:");
for (Integer key : hMap.keySet()) {
System.out.println(key + " => " + hMap.get(key));
}
}
}
Output:
HashMap:
1 => apple
2 => banana
3 => date
Related Collections Interview QA
- map() vs flatMap() in Java
- Collections vs Streams
- ArrayList vs Vector
- Iterator vs ListIterator
- HashMap vs HashTable
- HashSet vs HashMap
- Array vs ArrayList
- Fail-Fast Iterators vs Fail-Safe Iterators
- HashMap vs ConcurrentHashMap
- LinkedList vs ArrayDeque
- LinkedList vs Array
- LinkedList vs Doubly LinkedList
- Enum vs EnumSet in Java
- HashMap vs. TreeMap in Java
- Synchronized Collections vs. Concurrent Collections
Collection Framework
Interview Questions
Java
X vs Y
Comments
Post a Comment