Sobes.tech
Junior — Middle

Can you explain the concept of HashMap and how it works for storing key-value data?

sobes.tech AI

Answer from AI

HashMap is a data structure that stores key-value pairs and provides fast access to values by key.

How it works:

  1. The key goes through a hash function, which calculates an index in an array (bucket).
  2. The value is stored in this bucket along with the key.
  3. When searching by key, the hash is recalculated, and the corresponding index is checked.

If multiple keys have the same hash (collision), they are stored as a list or tree in the same bucket.

This allows operations like insert, search, and delete to be performed in approximately constant time (O(1)) on average.

Example in Java:

HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 5);
int count = map.get("apple"); // returns 3

Thus, HashMap is convenient for fast data access by a unique key.