It's not clear what you mean by "hashCode() method uses class to calculate the hashcode?". If you look at the signature of the Object.hashCode()
method, you'll realize that
- It is an instance method that any Java class can override.
- If a class (that, by default, extends the
java.lang.Object
class) overrides this method, then it can take care of creating a meaningful hash code for instances of that class. This helps, among other things, the instances of this class to be the keys in a hash table (realized using a java.util.Hashtable
or a java.util.HashMap
).
If you look at some of the standard library (JDK) class implementations of this method, you'll see that these classes implement this method meaningfully.
The hashCode()
implementation of a java.lang.Integer
class correctly chooses to just return the integer value an instance of that class represents.
The hashCode()
implementation of a java.lang.String
class is a little more involved and you'll find it in the source code:
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
There's a lot going on here for performance (and correctness) reasons, but you can get an idea that the hash code of a string is based on the characters that the string is made of.