Junior — Middle
What are the differences between HashMap and Set data structures in the context of their usage?
sobes.tech AI
Answer from AI
HashMap and Set are different data structures with different purposes and usage features:
-
HashMap is a collection of key-value pairs. It allows storing and quickly retrieving a value by its key. Keys are unique, values can repeat.
-
Set is a collection of unique elements without keys. It is designed to store a set of unique objects.
Main differences:
- In HashMap, each element is a pair (key, value), while in Set, it is just an element.
- HashMap allows quick lookup of a value by key, Set checks for the presence of an element.
- Set is often implemented based on HashMap, where elements act as keys, and values are dummy.
Example usage:
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 5);
Set<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
In conclusion, choose HashMap if you need to store key-value pairs, and Set if you need to store unique elements without values.