-4

Even if you have two different strings with the same value, they will have the same hashcode.

In the below example HashCode is the same? But the memory address is the same? How I can get it in java.  

jshell> var a = new String("Ranga")

a ==> "Ranga"

jshell> var b = new String("Ranga")

b ==> "Ranga"

jshell> a.hashCode()

$31 ==> 78727449

jshell> b.hashCode()

$32 ==> 78727449

jshell> a == b

$33 ==> false

  • 5
    Why? What is the problem you are trying to solve or thing you are trying to do? Thinking about memory address in Java means you're already on the wrong track... – John3136 Nov 17 '19 at 02:34
  • You cannot access memory locations in java. Even if you could, what would be the use of it? You cannot work with it. – f1sh Nov 17 '19 at 02:41
  • The question that you should ask yourself is, "does Java has pointers like C/C++?" and then you will be able to answer this question yourself. – Shankha057 Nov 17 '19 at 02:58
  • hashCode() != memory location. In the current implementation of hotspot, the identityHashCode does not depend on the memory location. – Johannes Kuhn Nov 17 '19 at 03:32
  • if you can add some refer links that will be helpful @JohannesKuhn – Ryuzaki L Nov 17 '19 at 03:35
  • @Deadpool https://srvaroa.github.io/jvm/java/openjdk/biased-locking/2017/01/30/hashCode.html – Johannes Kuhn Nov 17 '19 at 03:41
  • https://www.sololearn.com/Discuss/49708/can-we-print-address-of-an-object-in-java-if-yes-then-how-is-it-possible – Ajay Sharma Nov 17 '19 at 03:43
  • @AjaySharma the most "useful" thing in this "discussion" is that Unsafe might have something. After looking through the methods of Unsafe, I could not find anything that would return an address for an object (which might change btw). – Johannes Kuhn Nov 17 '19 at 03:53

1 Answers1

1

If you want to see the original hashCode for the String before it was altered you can do this:

String foo = ...some string
System.out.println(System.identityHashCode(foo));

According to the documenation for the hashCode

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.)

WJS
  • 36,363
  • 4
  • 24
  • 39