Junior — Middle
In which cases is it recommended to use the HashMap data structure?
sobes.tech AI
Answer from AI
HashMap in Java is recommended when you need to efficiently store key-value pairs with quick access by key. Main use cases:
- When high speed of insert, delete, and search operations is important (usually O(1) on average).
- When the order of elements does not matter, as HashMap does not guarantee traversal order.
- For implementing caching, indexing, and other structures where fast access by a unique key is required.
Example:
Map<String, Integer> wordCount = new HashMap<>();
wordCount.put("apple", 3);
int count = wordCount.get("apple"); // 3