如何用Java编写平等方法 [英] How to Write an Equality Method in Java

查看:64
本文介绍了如何用Java编写平等方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑将平等方法添加到以下简单点类中:

Consider adding an equality method to the following class of simple points:

public class Point {

    private final int x;
    private final int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    // ...
}

//我对平等的定义

public boolean equals(Point other) {
  return (this.getX() == other.getX() && this.getY() == other.getY());
}

此方法有什么问题?乍一看,它似乎可以正常工作:

What's wrong with this method? At first glance, it seems to work OK:

Point p1 = new Point(1, 2);
Point p2 = new Point(1, 2);

Point q = new Point(2, 3);

System.out.println(p1.equals(p2)); // prints true

System.out.println(p1.equals(q)); // prints false

但是,一旦开始将点放入集合中,麻烦就开始了:

However, trouble starts once you start putting points into a collection:

import java.util.HashSet;

HashSet<Point> coll = new HashSet<Point>();
coll.add(p1);

System.out.println(coll.contains(p2)); // prints false

即使p1被添加到coll并且p1和p2是相等的对象,怎么可能不包含coll呢?

How can it be that coll does not contain p2, even though p1 was added to it, and p1 and p2 are equal objects?

推荐答案

虽然在实现 equals()时确实应该实现 hashCode(),但是不会引起您的问题.

While it is true that you should implement hashCode() when you implement equals(), that is not causing your problem.

这不是您要查找的 equals()方法.equals方法必须始终具有以下签名:公共布尔equals(Object object)".这是一些代码.

That is not the equals() method you are looking for. The equals method must always have the following signature: "public boolean equals(Object object)". Here is some code.

public boolean equals(Object object)
{
  if (object == null)
  {
    return false;
  }

  if (this == object)
  {
    return true;
  }

  if (object instanceof Point)
  {
    Point point = (Point)object;
    ... now do the comparison.
  }
  else
  {
     return false;
  }
}

Apache EqualsBuilder类对于equals实现很有用.该链接是较旧的版本,但仍然适用.

The Apache EqualsBuilder class is useful for equals implementations. The link is an older version, but still applicable.

如果您喜欢Apache EqualsBuilder,则可能会喜欢 Apache HashCodeBuilder类.

If you liked the Apache EqualsBuilder, you will probably like the Apache HashCodeBuilder class as well.

编辑:更新了标准快捷方式的equals方法示例.

updated the equals method example for standard shortcuts.

这篇关于如何用Java编写平等方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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