在Java中覆盖equals()和hashCode()

问题描述:


可能重复:

覆盖Java中的equals和hashCode

全部,

我已经定义了我的类,并且还要覆盖equals()和hashCode()方法。但我不知道具体应该为我自己的课程实现这些方法。任何人都可以对自定义类的这些方法的实现有所了解吗?

I have defined my class and which to override equals() and hashCode () methods as well. But I have no idea of what specifically these methods should be implemented for my own class. Can anyone please shed some light on the implementation of these methods for custom classes?

你说你已经知道你的哪一个了自定义类需要覆盖hashCode / equals吗?然后您还知道哪些属性(全局变量)确定每个类的相等性。

You say you already know which one of your custom classes need to override hashCode/equals? Then you also know what attributes (global variables) determine equality of each class.

当您了解这些属性时,您可以手动或通过使用现代IDE(如Eclipse,NetBeans等)生成方法来实现hashCode / equals。在Eclipse中有一个选项名为Generate hashCode()和equals()在Source菜单下

When you know these attributes you can implement hashCode/equals either manually or by generating the methods using a modern IDE such as Eclipse, NetBeans, etc. In Eclipse there's an option named "Generate hashCode() and equals()" under the "Source" menu