Java String: Is hashcode hashvalue?

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

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

If we use a HashTable or HashMap , and the size cannot fit into more elements, then these collections will be resized to accommodate more elements.
This means that each saved item needs to be rephrased to calculate a new position in a new larger table.

My question is the following (which is true above):
I read that String computes its hashcode using the characters it stores, and additionally that hashvalue is stored internally (cached) for better performance, since it does not need to be recalculated.

This is the part that I do not get. If hashcode based on the characters that String stores, then how is the position calculated in a HashTable ?

Is there any additional logic using hashcode from String ? So String hashcode is actually not hashvalue ?

+4
source share
1 answer

The hash code does not change. Only the item in the internal table. Open the HashMap and see:

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

The index inside the table (array, in fact) is determined based on the hash and size of the array.

So, when "re-writing" occurs, it uses the same hash code, but has a different length, which means that the item is placed in another bucket.

+2
source

Source: https://habr.com/ru/post/1393262/


All Articles