Junior
What are HashMap and Set, and in which cases is it better to use them?
sobes.tech AI
Answer from AI
HashMap is a collection that stores key-value pairs. Keys are unique, while values can repeat. It uses hashing for fast access (on average O(1)) to elements by key.
Set is a collection that stores unique elements. It does not guarantee order unless a specific implementation is used (e.g., LinkedHashSet). Operations like adding, removing, and checking for an element are generally performed in O(1). There are various implementations, for example:
HashSet: Does not guarantee order of elements.LinkedHashSet: Maintains insertion order.TreeSet: Stores elements in sorted order.
When to use:
- HashMap:
- When efficient search, insertion, or deletion of elements by key is needed.
- For storing associative data (e.g., a dictionary).
- When quick existence check of a value by key is required.
- Set:
- When only unique elements need to be stored.
- For efficient existence checks within a collection.
- For set operations (union, intersection).
Example of using HashMap:
// Creating a HashMap
HashMap<String, Integer> ages = new HashMap<>();
// Adding elements
ages.put("Alice", 30);
ages.put("Bob", 25);
ages.put("Charlie", 35);
// Getting value by key
int bobAge = ages.get("Bob"); // bobAge = 25
// Checking if key exists
boolean containsAlice = ages.containsKey("Alice"); // containsAlice = true
Example of using HashSet:
// Creating a HashSet
HashSet<String> names = new HashSet<>();
// Adding elements
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("Alice"); // Will not add, as Alice already exists
// Checking if element exists
boolean containsBob = names.contains("Bob"); // containsBob = true
// Iterating over elements
for (String name : names) {
System.out.println(name);
}