如何在Java中正确实现equals [英] How to properly implement equals in Java

查看:82
本文介绍了如何在Java中正确实现equals的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在一些类A中实现equals方法。类A具有一个Enum类型的有序集合,而我想实现的行为是,对于具有完全相同的Enum值的两个类A实例,equals返回true在集合中(完全相同的位置)。

I need to implement the equals method in some class A. Class A has an orderer collection of Enum type, and the behaviour I want to achive is that equals returns true for two instances of Class A that have exactly the same Enum values in the collection (in exactly the same positions of the collection).

由于我是Java新手,因此遇到了问题,我不知道该怎么做正确地实现equals或hashcode方法,所以任何帮助都是不错的:)

As I'm new to java, I'm having problems with this, and I dont know how to properly implement equals or the hashcode methods, so any help would be good :)

推荐答案

如果您使用的是eclipse(netbeans与大多数Java IDE一样,它具有类似的功能),您只需进入源菜单,然后选择生成hashcode()和equals()。然后,选择要考虑的字段(在您的情况下为枚举值的列表。

If you're using eclipse (netbeans has similar features, as do most java IDEs), you can simply got to the "Source" menu, and choose "Generate hashcode() and equals()". Then you select the fields you want to be considered (in your case the list of enum values.

话虽如此,假设您已经有了枚举,那么下面的代码eclipse是为我生成的。不是那个哈希码通常涉及素数,乘法和加法,这往往会给你一些合理的值分布。

That being said, assuming you already have the enum, here's the code that eclipse generated for me. Not that hashcode usually involves a prime number, as well as multiplication and addition. This tends to give you somewhat decent distribution of values.

public class Foo {
   private List<FooEnum> enumValues;

   @Override
   public int hashCode() {
       final int prime = 31;
       int result = 1;
       result = prime * result
               + ((enumValues == null) ? 0 : enumValues.hashCode());
       return result;
   }

   @Override
   public boolean equals(Object obj) {
       if (this == obj)
           return true;
       if (obj == null)
           return false;
       if (getClass() != obj.getClass())
           return false;
       Foo other = (Foo) obj;
       if (enumValues == null) {
           if (other.enumValues != null)
               return false;
       }
       else if (!enumValues.equals(other.enumValues))
           return false;
       return true;
   }


}

这篇关于如何在Java中正确实现equals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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