Junior — Middle
How is the performance of insert, search, and delete operations in HashMap evaluated?
sobes.tech AI
Answer from AI
In Java, HashMap provides an average time complexity of O(1) for insert (put), search (get), and delete (remove) operations. This is achieved by using a hash function for quick access to buckets.
However, in the worst case, when there are many collisions (elements fall into the same bucket), operations can degrade to O(n), where n is the number of elements in the bucket. Modern implementations of HashMap (starting from Java 8) use balanced trees (e.g., red-black trees) to reduce access time to O(log n) in such cases.
Thus:
- Average: insert, search, delete — O(1)
- Worst case: O(log n) (with Java 8 and above)
Example of insertion and search:
HashMap<String, Integer> map = new HashMap<>();
map.put("key", 42); // insertion
Integer value = map.get("key"); // search