Java recreate string from hashcode

Viewed 24197

Is there any way that I can use a hashcode of a string in java, and recreate that string?

e.g. something like this:

String myNewstring = StringUtils.createFromHashCode("Hello World".hashCode());
if (!myNewstring.equals("Hello World"))
    System.out.println("Hmm, something went wrong: " + myNewstring);

I say this, because I must turn a string into an integer value, and reconstruct that string from that integer value.

6 Answers

You could do something like this:

char[] chars = "String here".toCharArray();
int[] ints = new int[chars.length];
for (int i = 0; i < chars.length; i++) {
    ints[i] = (int)chars[i];
}

Then:

char[] chars = new char[ints.length]
for (int i = 0; i < chars.length; i++) {
    chars[i] = (char)ints[i];
}
String final = new String(chars);

I have not actually tested this yet... It is just "concept" code.

Related