Sobes.tech
Junior — Middle

Kas saaksite selgitada, kuidas pääseb HashMap-struktuuri elemendile?

sobes.tech AI

Vastus AI-lt

In Java, HashMap is implemented based on an array of buckets, each of which contains a linked list or a tree (from Java 8) of elements with the same hash code.

Access to an element is done as follows:

  1. The hash code of the key is calculated using hashCode().
  2. The hash code is transformed into an index of the bucket array (usually via the operation hash & (capacity - 1)).
  3. In the selected bucket, the element with the key equal to the searched key is looked for (comparison via equals()).
  4. If the element is found, the associated value is returned.

Example:

HashMap<String, Integer> map = new HashMap<>();
map.put("key", 42);
Integer value = map.get("key"); // hash is calculated, bucket is selected, element is searched

Thus, access to an element consists of calculating the hash, selecting the bucket, and searching by key inside the bucket.