从多个Java字符串对象创建哈希 [英] Creating a hash from several Java string objects

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

问题描述

实现类似方法的最快和更强大(就唯一性而言)的方法是什么?

What would be the fastest and more robust (in terms of uniqueness) way for implementing a method like

public abstract String hash(String[] values);

values [] 数组有100到1,000个成员,每个成员只有几十个字符,并且每次在不同的 values [] 数组中,该方法需要运行大约10,000次/秒。

The values[] array has 100 to 1,000 members, each of a which with few dozen characters, and the method needs to be run about 10,000 times/sec on a different values[] array each time.

是否应使用 StringBuilder 缓冲区构建长字符串,然后在缓冲区内容上调用哈希方法,或者它是否更好继续从 values [] 调用每个字符串的哈希方法?

Should a long string be build using a StringBuilder buffer and then a hash method invoked on the buffer contents, or is it better to keep invoking the hash method for each string from values[]?

显然是至​​少64位的哈希值是否需要(例如,MD5)以避免碰撞,但是有什么更简单,更快的可以做到,质量相同吗?

Obviously a hash of at least 64 bits is needed (e.g., MD5) to avoid collisions, but is there anything simpler and faster that could be done, at the same quality?

例如,

public String hash(String[] values)
{
    long result = 0;

    for (String v:values)
    {
        result += v.hashCode();
    }

    return String.valueOf(result);
}


推荐答案

绝对不要使用普通此外,由于其线性属性,但您可以稍微修改您的代码以实现非常好的分散。

Definitely don't use plain addition due to its linearity properties, but you can modify your code just slightly to achieve very good dispersion.

public String hash(String[] values) {
  long result = 17;
  for (String v:values) result = 37*result + v.hashCode();
  return String.valueOf(result);
}

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

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