Sobes.tech
Senior

How to convert hashCode (int, possibly negative) into a bucket array index?

sobes.tech AI

Answer from AI

To convert hashCode (an integer, possibly negative) into a bucket array index, the following scheme is usually applied:

  1. Convert hashCode to a non-negative number. This is often done using a bitwise AND with the mask 0x7FFFFFFF (to reset the sign):
int positiveHash = hashCode & 0x7FFFFFFF;
  1. Take the remainder of dividing by the array size (the array length should be positive):
int index = positiveHash % buckets.length;

This guarantees that the index will be in the range from 0 to buckets.length - 1.

Example:

int hashCode = key.hashCode();
int index = (hashCode & 0x7FFFFFFF) % buckets.length;
How to convert hashCode (int, possibly negative) into… - sobes.tech