user2599052
user2599052

Reputation: 1136

how does hashmap ensure that each hash value is assigned a unique index in the hash table

I want to understand how hash() and indexOf() methods of HashMap assign a unique index in hash table to a hashmap. In other words, why it is not possible for multiple hash values to be mapped to the same index.

Upvotes: 2

Views: 759

Answers (1)

copeg
copeg

Reputation: 8348

In HashMap, the underlying bucket array size is set upon initialization and may be resized accordingly - the bucket index of an item (in indexFor) is generated by key.hashCode() % (table.length - 1).

how does hashmap ensure that each hash value is assigned a unique index in the hash table

The do not have to be unique (see below)

why it is not possible for multiple hash values to be mapped to the same index

This is possible - more than one Entry (key/value pair) can be mapped to a single bucket. A proper hash table implementation overcomes this by having each bucket capable of holding more than a single Entry. HashMap in particular uses a linked list - if an item maps to an already occupied bucket, that item is added to the beginning of the bucket's linked list.

Upvotes: 4

Related Questions