Cratylus
Cratylus

Reputation: 54094

Java String: Is hashcode actually the hashvalue?

A hastable uses some hash function on an object to store.

This hash function essentially calculates the position of the object in the table.

If we use a HashTable or HashMap and the size can not fit more elements then these collections are resized to accomodate more elements.
This means that each stored element must be rehashed to calculate the new position in the new bigger table.

My question is the following(that the above are correct):
I read that String calculates its hashcode by using the characters that it stores and additionally that the hashvalue is stored internally (cached) for best performance since it does not have to be recalculated.

This is the part I don't get.If the hashcode is based on the characters the String stores then how is the position in the hashtable calculated?

Is there some extra logic using the hashcode of String? So the String's hashcode is not actually the hashvalue?

Upvotes: 4

Views: 556

Answers (1)

Bozho
Bozho

Reputation: 597342

The hashcode is not changed. Only the position in the internal table is. Open HashMap and see:

static int indexFor(int h, int length) {
    return h & (length-1);
}

The index within the table (array, actually) is determined based on the hash and the size of the array.

So, when "rehashing" happens, it uses the same hashcode, but a different length, which means the element is put in a different bucket.

Upvotes: 2

Related Questions