Sobes.tech
Junior — Middle

Can you explain how the HashMap data structure works and how it provides fast access to elements?

sobes.tech AI

Answer from AI

HashMap is a data structure that stores key-value pairs and provides quick access to elements.

Working principle:

  1. The key passes through a hash function, which calculates an index in the array (bucket).
  2. At this index, a list or tree of elements with the same hash is stored (to handle collisions).
  3. When searching by key, the hash is first calculated, then the element with the exact key match is searched in the corresponding bucket.

Thanks to hashing, access to elements usually occurs in O(1) time, which is much faster than linear search.

Example in Java:

HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 5);
int value = map.get("apple"); // quickly retrieves 5

Thus, HashMap provides efficient access and storage of data by key.