Answer the question
In order to leave comments, you need to log in
I'm confused about HashMap, how will it be right?
Hello, I started my acquaintance with the HashMap class in Java, and due to discrepancies in different sources that confused me, a question arose about hashing and finding the right index in the hash table.
A hash function and a hash code seem to be different concepts, but for some reason in some articles I have seen more than once that they are mixed and equated, which introduces me into additional confusion. And most of the articles with a detailed analysis are quite old. For example, in Java 7, the index of the desired cell was calculated in the indexFor method, but now it is not there (I use JDK 12). I ask for help so that I can figure it out and not stray around this for the third day.
I tried to look in the documentation (I'm not a programmer, I'm learning the language) and tried to find something. Inside the array, cells contain nodes (Node class). This class has a hash field - is this the hash code?
There is also a hashCode() method, which is calculated like this:
return Objects.hashCode(key) ^ Objects.hashCode(value);
But I thought that the hash code is calculated only by the key? It is the result of this method that will lie in the hash field? And when overriding the hashCode() method, do we override this particular method?
But further down the class I find the following method: static final int hash(Object key) which already evaluates to:
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
The description of this method in the documentation gave me almost nothing. Is it a hash function that calculates the desired array cell? If not, where is she?
When adding an object to the HashMap, the hash (hash code) of the key is calculated, which we get as a result of the hashCode () method, and then the hash function as a result of its work "receives" the indices of the desired array cells to insert?
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question