在java中实现equals方法

这是我对Coor类的equals类的实现,它只包含2个整数x和y。 这是实现这种方法的正确方法吗?

public boolean equals(Object obj) { if (obj == null || obj.getClass() != this.getClass()) { return false; } Coor temp = (Coor) obj; if (temp.x == this.x && temp.y == this.y) { return true; } else { return false; } } 

您可以再添加一个检查以reflection相等(等于self):

  public boolean equals(Object obj) { // Reflexive equality: did I get passed myself? if(this == obj){ return true; } if (obj == null || obj.getClass() != this.getClass()) { return false; } Coor temp = (Coor) obj; return temp.x == this.x && temp.y == this.y; } 

是的,它会的。

还要确保覆盖你的hashCode()方法 – 永远不要覆盖一个而不做另一个,它会混淆你的集合中的地狱。

你的情况可以使用一个哈希,它只是简单地移动一个int 32位并将其添加到另一个创建一个完全唯一的long(在这种情况下是一个完美的哈希函数 – 没有冲突)

好像没问题。 为简洁起见,您可以:

 return temp.x == this.x && temp.y == this.y 

代替

 if (temp.x == this.x && temp.y == this.y) { return true; } else { return false; } 

另外,请记住对象合同(严重!)。

请参阅此处接受的答案: 在Java中覆盖equals和hashCode时应考虑哪些问题?

这可以为您节省大量未来的头痛。

看一下这个:

http://www.javapractices.com/topic/TopicAction.do?Id=17

如果那篇文章太详细了,那么缺点是:你的实现是正确的,但你应该记住一些其他的事情:

  1. 您还必须实现hashCode。

  2. equals将不再使用该对象的身份。 听起来不是那个问题。

  3. 您可以将@Override注释添加到equals方法中。

这是一种更直接的方式:

 public boolean equals(Object other) { return other instanceof Coor && ((Coor) other).x == x && ((Coor) other).y == y } 

我相信这会很快发挥作用。 我这样说是因为:

  1. 它很好地处理null /不正确的类型。
  2. 执行x.equals(y)将产生与y.equals(x)相同的结果。
  3. 执行x.equals(x)将返回true。
  4. 执行x.equals(y)== true和y.equals(z)== true意味着x.equals(z)== true

这个问题之前肯定已被问过很多次了。 请参阅此处: 在Java中覆盖equals和hashCode 。 一本名为Effective Java的书也非常详细地讨论了这个主题,并且特定章节与之相关联。

关于如何覆盖equals和hashCode只有一个来源:Joshua Bloch的“Effective Java”的第3章 。

如果你有一个好的IDE,比如IntelliJ,它会为你生成equals和hashCode。