Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashCode

 
Eric Sexton
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there a way to convert a has code to string? I would like calculate a hashCode for the string and then convert it back.
 
Joe Ess
Bartender
Posts: 9312
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A hash code is an integer (primitive). You can convert it to a String by using String.valueOf(int i).
 
Eric Sexton
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dang, I wasn't clear. Sorry for the confusion.
I want to take a string such as "Hello World", and display it's hashCode.
That part is easy enough. Now I want to convert that hashCode back into the String "Hello World". Is that possible?
 
Joe Ess
Bartender
Posts: 9312
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Eric Sexton:

Now I want to convert that hashCode back into the String "Hello World". Is that possible?

[/QB]
No. A hash code is intended to give one a good distribution when storing objects in a hash table. There is no way to tell from a hash code what type an object is or what its value(s) is/are.
 
John Smith
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no way to tell from a hash code what type an object is or what its value(s) is/are.
Well, there is a way to reconstruct a String value from its hashcode, but it's very ugly and not reliable. The only purpose of doing it may be as an exercise to see how the hashCode() works in a particular JDK implementation, or to have it formulated as a pure and theoretical math problem. So, while the reconstruction code below works, don't use it, -- for all intents and purposes, the street from an object to its hash code is a one way street, just like Joe indicated.


Output:
original string is cat
reconstructed string is cat

[ October 06, 2003: Message edited by: Eugene Kononov ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic