0

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());

}

}

Tarang Hirani
  • 560
  • 1
  • 12
  • 43

3 Answers3

3

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.

Dici
  • 25,226
  • 7
  • 41
  • 82
  • But my code is evaluating the hashcode method on different objects, namely, str and strOne. Am i correct in this logic? – Tarang Hirani Jun 08 '15 at 19:17
  • 1
    They are different in terms of `==` (reference) but they are the same in terms of `equals` (logically equal) – Dici Jun 08 '15 at 19:19
1

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.)

Dan Getz
  • 8,774
  • 6
  • 30
  • 64
Tr1gZer0
  • 1,482
  • 11
  • 18
  • I think the part that is confusing me is that they are two different objects but have the same hashcode. Rule of thumb says that if two objects are equal using the .equals method, they will have the hashcode. The fact that they are 2 different objects is confusing me. Help! – Tarang Hirani Jun 08 '15 at 19:11
  • The documentation gives the formula for how they evaluate hash for String. They never refer to the reference of the object in this calculation. – Tr1gZer0 Jun 08 '15 at 19:13
  • Not sure why a down vote was given... I even gave the exact formula. :-) – Tr1gZer0 Jun 08 '15 at 19:17
  • @machsleep No, the *link* gave the exact formula. You didn't. Include the relevant bits that answer the question directly here, keeping the link as a reference, or add this as a comment instead. This is basically a link-only answer. – tnw Jun 08 '15 at 19:18
  • @TarangHirani try doing `"String".equals(new String("String"))`... it returns `true`, so what you said applies to this case : `two objects equal with the equal method have the same hashCode` – Dici Jun 08 '15 at 19:27
  • Should I just remember that as a rule of thumb? – Tarang Hirani Jun 08 '15 at 19:37
0

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[];
Razib
  • 10,965
  • 11
  • 53
  • 80