Search code examples
javahashcodeobject-reference

hashCode as object ref in JDK 8


From what i know, jdk 8 now is assigning as hashCode the memory address of the object.

And, obj1 = obj2 returns true iff the obj1 is obj2, i.e., they're sitting at the same memory location.

However, the following code executes the "else" part-- not the "then" part of the if-stat which is what i expect:

String h1 = "heya"; 
String h2 = new String ("heya");
System.out.println("hashCodes "+h1.hashCode()+" "+h2.hashCode()); 

if (h1 == h2) 
        System.out.println("yeah - the same ");  
else System.out.println("nope-- difft objects ");  

What am i missing here?

TIA.


Solution

  • h1 and h2 are not sitting in the same memory location. You are calling a new String("heya") so the JVM will create a new instance of String. Therefore, h1 == h2 is false. The hasCode is the same because it is based on the char composing the String. Using equals method instead of == will return true.