2

如果这个问题真的很奇怪,我很抱歉。我正在将数据发送到我不希望发送重复数据的队列。该程序无法防止重复的数据项,只是接受它们,但我相信队列 ID 必须是唯一的,我可以自己指定这些。所以我想尝试根据我发送的数据生成我的 ID。

假设我有两个字符串:

hello, SO how are you? //base case
hello, SO how are you? //same
hello, SO how are You? //different, notice the capital Y
What up, SO! //completely different

我可以在Java中将它转换成什么来匹配上面的前两个字符串但使另外两个唯一?到目前为止我还没有尝试太多(因为我不确定将其转换为最好的东西是什么),但我确实玩了一下,GZIPOutputStream但大小似乎有点相似,我不确定它是否是最有效的(即最小的尺寸,比如一些疯狂的十六进制字符或其他东西)。

我希望有人理解我的要求,但如果没有,请告诉我,我会尽力澄清。

编辑:对不起,我不只是想要字符串的东西,我也在处理列表(也许还有字典)。对于那个很抱歉

谢谢

代码:

public class hashtest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        convert("hello world"); //same
        convert("hello world"); //same

        convert("hello world!"); //exclamation mark
        convert("hello World"); //capital W

        convert_list(new int[] {5, 2, -3}); //same
        convert_list(new int[] {5, 2, -3}); //same
        convert_list(new int[] {5, 3, -3}); //different
        convert_list(new int[] {5, 2, -4}); //different

    }

    private static void convert_list(int[] is) {
        // TODO Auto-generated method stub
        System.out.println("word is " + is);
        System.out.println("hashcode is " + is.toString());
        System.out.println("****");
    }

    private static void convert(String string) {
        // TODO Auto-generated method stub
        System.out.println("word is " + string);
        System.out.println("hashcode is " + string.hashCode());
        System.out.println("****");
    }

}
4

2 回答 2

3

将其String本身用作队列 ID,或者如果您需要Integer使用String.hashCode()hashCode()为相同的字符返回相同的值)

编辑:

如果您的对象实际上不是字符串,最好的方法是实现您自己的hashCode()方法。或者对于“快速而肮脏的”,您可以简单地将其呈现为字符串(从唯一位组成一个唯一字符串)并在其上调用字符串的 hashCode() 。

编辑(更多):

问题是您使用的.toString()是数组,它在 java 中没有为数组类实现,所以它回退到 Object 的实现,即使内容相同,它对于每个数组都是唯一的。

幸运的是,JDK 提供了答案:使用实用程序方法Arrays.toString()

private static void convert_list(int[] is) {
    // TODO Auto-generated method stub
    System.out.println("word is " + is);
    System.out.println("hashcode is " + Arrays.toString(is));
    System.out.println("****");
}
于 2012-04-14T16:31:09.987 回答
1

如果您需要一些不仅适用于String您的东西,您可以选择SHA-1算法。

在java中你可以用这种方式

MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
byte[] buf = crypt.digest("hello, SO how are you?".getBytes());

它适用于字节数组,因此您可以将类型转换为 byte[] 然后使用它。

结果是byte[]长度为 20 的 a。因此,如果您的原始数据长度大于 20 个字节,这是一个不错的选择。

关于两个不同输入产生相同结果的概率,请阅读这篇文章。或者在网上搜索更多的技术资料。无论如何,概率非常非常低。

于 2012-04-14T17:05:18.427 回答