aspose file tools*
The moose likes Beginning Java and the fly likes hashCode Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "hashCode" Watch "hashCode" New topic
Author

hashCode

Eric Sexton
Ranch Hand

Joined: Sep 12, 2003
Posts: 133
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

Joined: Oct 29, 2001
Posts: 8997
    
    9

A hash code is an integer (primitive). You can convert it to a String by using String.valueOf(int i).


[How To Ask Questions On JavaRanch]
Eric Sexton
Ranch Hand

Joined: Sep 12, 2003
Posts: 133
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

Joined: Oct 29, 2001
Posts: 8997
    
    9

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

Joined: Oct 08, 2001
Posts: 2937
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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: hashCode