Sobes.tech
Senior

Tell me about HashMap: what is it for and how does it work?

sobes.tech AI

Answer from AI

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

Purpose:

  • Fast search, insertion, and deletion of elements (usually in near O(1) time).
  • Convenient for implementing dictionaries, caches, indexes.

Working principle:

  • The key is transformed into a hash code using a hash function.
  • The hash code is used to determine the index in an array (bucket) where the value is stored.
  • If multiple keys have the same hash (collision), they are stored in a chain or structure within the bucket.
  • When searching by key, the hash is first computed, then elements in the bucket are iterated for an exact match.

Example of usage in Java:

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

HashMap provides efficient storage and quick access to data by key, making it one of the most popular collections in Java.

Tell me about HashMap: what is it for and how does it… - sobes.tech