Java从哈希码重新创建字符串 [英] Java recreate string from hashcode

查看:125
本文介绍了Java从哈希码重新创建字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法可以在java中使用字符串的哈希码,并重新创建该字符串?

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.

推荐答案

这是不可能的。 String的哈希码是有损的;许多String值将导致相同的哈希码。整数具有32位位置,每个位置具有两个值。即使只是将32个字符的字符串(例如)(每个字符都有很多可能性)映射到32位而没有冲突,也无法映射。他们只是不适合。

This is impossible. The hash code for String is lossy; many String values will result in the same hash code. An integer has 32 bit positions and each position has two values. There's no way to map even just the 32-character strings (for instance) (each character having lots of possibilities) into 32 bits without collisions. They just won't fit.

如果你想使用任意精度算术(比如BigInteger),那么你可以把每个字符作为一个整数并将它们连接起来一起。 Voilà。

If you want to use arbitrary precision arithmetic (say, BigInteger), then you can just take each character as an integer and concatenate them all together. Voilà.

这篇关于Java从哈希码重新创建字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆