0

During an interview, interviewer asked me - is the hashcode calculated based on Class?

I told him, hashcode will be calculated based on the fields or variables in the class. He gave me some expression which makes me think like the answer is wrong.

I read the java doc but I didn't get the clear idea. I read the post how is hascode calculated in java In that there is Integer hashcode and Character hashcode. Could anyone tell me how the hashcode for a particular object will be calculated and what is Interger hashcode and String hashcode?

Community
  • 1
  • 1
Dinesh Kumar J
  • 167
  • 1
  • 1
  • 7

2 Answers2

1

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

  1. It is an instance method that any Java class can override.
  2. 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.

Kedar Mhaswade
  • 4,535
  • 2
  • 25
  • 34
1

If you consider hashCode() method of the Object class it is calculated by converting address of the object to integer.

Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()

Dhruv Kapatel
  • 873
  • 3
  • 14
  • 27