简体   繁体   English

java-为对象生成唯一的md5哈希

[英]java - generate unique md5 hash for objects

I need to generate unique hash for objects to identify objects with the same exact attributes. 我需要为对象生成唯一的哈希值,以标识具有相同确切属性的对象。

After reading a bit on the subject I decided its best to use MD5 hashing rather than java hashCode (I have a large number of objects, around 200,000-300,000). 在阅读了有关该主题的内容之后,我决定最好使用MD5哈希而不是Java hashCode(我有大量的对象,大约200,000-300,000)。

I found many examples on how to do MD5 hashing on a string, but didn't find how to do it on an object, so that it will really be unique according to the object's attributes. 我找到了许多有关如何对字符串进行MD5哈希处理的示例,但没有找到如何对对象进行处理,因此根据对象的属性,它实际上是唯一的。

Hash code of an object does not need to be unique. 对象的哈希码不需要唯一。 By the way it is impossible 顺便说一句不可能

Hash code must comply to the following contract: 哈希码必须遵守以下合同:

  • It should return the same value every time it is invoked on the same object in the same state. 每次在相同状态下对同一对象调用时,它应返回相同的值。
  • If two objects are equal according to Object::equals then the hashCode should return the same. 如果两个对象根据Object::equalshashCode应该返回相同的值。

Most of IDEs can generate the method hashCode() but there are some tools even in JDK for generating hashcode eg. 大多数IDE都可以生成hashCode()方法,但是即使在JDK中也有一些工具可以生成哈希码,例如。 java.util.Objects.hash(Object...) . java.util.Objects.hash(Object...)

You can read a great summary here 您可以在此处阅读摘要

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

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