Sobes.tech
Senior

Tell me about the HashMap data structure.

sobes.tech AI

Answer from AI

HashMap in Java is an implementation of the hash table data structure that stores key-value pairs. The main principle of operation is computing the hash code of the key, which is used to determine the index in the array of buckets.

Each bucket contains a linked list or a tree (starting from Java 8, if there are many elements) to resolve collisions — situations where different keys have the same hash.

When adding an element to HashMap:

  • The hash code of the key and the bucket index are computed.
  • If the bucket is empty, the element is placed there.
  • If the bucket is occupied, a search is performed through the list/tree to replace or add a new element.

When searching for an element by key:

  • The bucket index is computed based on the hash of the key.
  • The element with the matching key is searched within the bucket.

HashMap does not guarantee the order of elements. Important characteristics:

  • Access time — on average O(1), but in the worst case, it can be O(n).
  • When a certain load factor (usually 0.75) is exceeded, the array is expanded and elements are redistributed.

Example of creating and using HashMap:

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