• Post Reply Bookmark Topic Watch Topic
  • New Topic

What is the difference between "Text" and new String ("Text);  RSS feed

 
Miri Yusifli
Ranch Hand
Posts: 43
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am learning string and i understand that new String create new object but why hashcodes of s1 and s2 are the same ? if i have  2 Text , their memory adresses and hashcodes should be different , is that true?



Result
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hash codes are not memory locations. While the implementation returned by Object.hashCode (and therefore any class that does not override the method) looks like a memory location, you can't assume it actually is.

In your case, the two hash codes are equal because String overrides hashCode to return something based on the content of the String. Since the two Strings have the same content, they have the same hash code.
 
Miri Yusifli
Ranch Hand
Posts: 43
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Spoor wrote:Hash codes are not memory locations. While the implementation returned by Object.hashCode (and therefore any class that does not override the method) looks like a memory location, you can't assume it actually is.

In your case, the two hash codes are equal because String overrides hashCode to return something based on the content of the String. Since the two Strings have the same content, they have the same hash code.


So, how can I print their memory addresses?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Miri Yusifli wrote:
So, how can I print their memory addresses?


First, as an FYI, Java objects actually move. So, even if you do get an address, it may not be valid at the time that you use it.

To answer your question. There may be a library that does it, but barring that, the main option is likely to write a native method (via the C language).

Henry
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!