简体   繁体   English

如何从对象获取哈希/ md5?

[英]how can i get an hash/md5 from an object?

I have a class like this 我有这样的课

Class A{

  private String string1;
  private String string2;
  ..
  ..

  private String string19;

}

Some of the strings may be empty. 一些字符串可能为空。

I want to get an hash/identifier (string or number) for the instances of this class. 我想为此类的实例获取哈希/标识符(字符串或数字)。 I can use hashCode but i don't know if i can get some collision, i have a lot of instances of this class (about 4-5 million). 我可以使用hashCode,但是我不知道是否能遇到一些冲突,我有很多此类的实例(大约4-5百万)。

I need a fast way to get this hash. 我需要一种快速的方法来获取此哈希。

Thanks for the help. 谢谢您的帮助。

You could write a custom hashCode method that uses a slightly altered version of the hashCode algorithm in the String class. 您可以编写一个自定义的hashCode方法,该方法在String类中使用hashCode算法的稍微改动的版本。 From the Oracle documentation, the String hashCode is computed as follows: 从Oracle文档中,字符串hashCode的计算如下:

 s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

You could implement a modified version where you compute n over all the String objects in your class. 您可以实现一个修改后的版本,在其中对类中的所有String对象计算n This way you are not wasting space and time creating a concatenated String to do the same. 这样,您就不会浪费时间和空间来创建串联的String来执行相同的操作。 In some circumstances this might be fine, but with 4-5 million objects, you probably want to avoid that much churn. 在某些情况下,这可能很好,但是对于4-5百万个对象,您可能想要避免那么多的流失。

Source: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#hashCode%28%29 来源: http : //docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#hashCode%28%29

You can concatenate all of the strings, and then do a hash of your choosing on it. 您可以连接所有字符串,然后对其进行哈希选择。 If the string is null, you can use "Null" or any other string -- it really doesn't matter as long as you're consistent. 如果字符串为null,则可以使用“ Null”或任何其他字符串-只要保持一致,就没有关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM