java - why is the hashcode() returning the same integer?

345 views Asked by At

I am not exactly sure why the hashCode() method is returning the same value. Can someone provide more detailed explanation of this?

Source code (Java):

public class Equality {

public static void main(String [] args)
{
    String str = "String";
    String strOne = new String("String");



    System.out.println(str == strOne);
    System.out.println(str.equals(strOne));

    System.out.println(str.hashCode());
    System.out.println(strOne.hashCode());

}

}

3

There are 3 answers

2
Dici On

From the Javadoc :

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

Basically, a.equals(b) => a.hashCode() == b.hashCode() so two identical strings will surely have the same hashCode.

It seems to me that the behaviour you were expecting is the one of ==, but it clearly is not. == is the strongest equality in Java, because it compares the location in memory of two objects. equals comes just after it, it is a logical equality, two objects can be equal even if they have different memory locations. The hashCode has the weakest properties, quoted above.

6
Tr1gZer0 On

This should help your understanding. According to the Java 7 docs for String.hashCode() (I believe Java 6/8 should be similar or identical):

public int hashCode()

Returns a hash code for this string. The hash code for a String object is computed as

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)

0
Razib On

The hasCode() method applied on the value of String which is "String" both case.

Although you have created two reference of String type like this -

String str = "String";
String strOne = new String("String");  

But the hashCode() use the value assigned with the reference (str and strONe). Thats why the two hashCode() are equals.

Look at the hashCode() method of String class -

public int hashCode() {
    int h = hash;
        int len = count;
    if (h == 0 && len > 0) {
        int off = offset;
        char val[] = value;

            for (int i = 0; i < len; i++) {
                h = 31*h + val[off++];
            }
            hash = h;
        }
        return h;
    }  

and value is declared like this -

private final char value[];