可以我只用一个唯一的字段生成 hashcode() 和 equals() 吗?

huangapple go评论161阅读模式
英文:

Can I generate hashcode() and equals() with only one unique field?

问题

只考虑字段ID生成hashCode()和equals()是否可以?

英文:

Lets say, I have a class Student. Each student object has a unique field ( int ID ) plus other common fields (like String schoolName etc).

Now is it ok to generate hashcode() and equals() by considering ONLY the field ID ?

答案1

得分: 2

可以绝对使用ID作为哈希码和equals的依据。根据HashMap中的桶数量,具有不同ID的多个对象将共享相同的桶,然后equals方法将识别正确的对象。由于您计划使用唯一的ID,equals方法将比较ID与桶中每个对象(LinkedList/Tree)并识别唯一对象。

**但有一个注意事项。**如果ID是自增的,您可以在哈希码中使用ID,以便您的对象均匀分布在桶中。但是,如果您的ID字段具有某种模式,例如4、8、12、16等,您将在部分桶中放置大多数对象。在这种情况下,使用哈希码生成素数,因为素数是在桶中均匀分布的最佳候选者。

英文:

Yes, you can absolutely use ID for hashcode and equals. Based on the number of buckets in HashMap, multiple objects with different ID will share the same bucket and then the equals method will identify the right object. Since you are planning to use ID which is unique, equals method will compare the ID with each object in bucket -> LinkedList/Tree and identify the unique object.

However there is a catch. You can use ID in Hashcode if the ID is kind of an auto increment so that your objects are distributed evenly in the buckets. However if your ID field is some sort of pattern like 4, 8, 12, 16 etc., you will end up putting most of your objects in a portion of buckets. So in that case, use Hashcode to generate a prime number as prime numbers are best candidates for evenly distribution in Buckets.

答案2

得分: 1

  1. 意图:这取决于您的对象的意图和预期的受众。如果有这样一种情况,即学生结婚并更改了他们的姓氏。现在,如果您的代码依赖于.equals() 来确定是否有要保存的更改,那么这些更改将不会被捕捉到以供保存。对于学生对象上可能会更改的任何其他字段也是如此。

  2. 受众:如果您将您的对象打包成一个库并提供给他人使用,他们可能会期望只有在所有非瞬态字段都相等的情况下,Student对象的实例才相等。

英文:

It depends on the intent of your object and the intended audience.

  1. Intent: There could be a case where a student gets married and changes their last name. Now if your code relies on .equals() to determine if there are changes to save then the changes won't get picked up to be saved. The same is true for any other field that may change on the Student object.

  2. Audience: If you package your object into a library and give it to others. They may have an expectation that an instance of the Student object is equal if and only if all non-transient fields are equal.

huangapple
  • 本文由 发表于 2020年8月4日 02:11:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63234756.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定