Sobes.tech
Junior — Middle

Have there been situations where hashCode returned a negative value? How did you handle it?

sobes.tech AI

Answer from AI

Yes, the hashCode() method in Java can return negative values because it returns an int, which can be either positive or negative.

If you need to use hashCode for indexing in arrays or other data structures where the index must be non-negative, the following technique is usually applied:

int hash = obj.hashCode();
int positiveHash = hash & 0x7fffffff; // clears the sign bit, making the number positive
int index = positiveHash % array.length;

Alternatively, you can use Math.abs(), but with caution, as Math.abs(Integer.MIN_VALUE) returns a negative number:

int hash = obj.hashCode();
int positiveHash = (hash == Integer.MIN_VALUE) ? 0 : Math.abs(hash);
int index = positiveHash % array.length;

Thus, to avoid negative indices, you need to explicitly convert hashCode to a non-negative value.

Have there been situations where hashCode returned a… - sobes.tech