0

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.

user3880721
  • 613
  • 6
  • 16
  • @Aeshang - that's another issue -- that's how they were to me too but i'll be wondering abt that once I get passed this. what ur saying is that instantiating a new string by-passes interning that value and I agree. however, run n see the hashCode values in the above code. – user3880721 Sep 05 '14 at 18:38
  • 1
    `String` != `Object`. Different `hashCode` implementation. – Sotirios Delimanolis Sep 05 '14 at 18:38
  • 1
    The tutorial is misleading. `hashCode` doesn't need to have anything to do with memory addresses. – fgb Sep 05 '14 at 18:46

2 Answers2

0

The String class overrides hashCode().

jtahlborn
  • 52,909
  • 5
  • 76
  • 118
0

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.

ortis
  • 2,203
  • 2
  • 15
  • 18