如何检查价值平等? [英] How to check for value equality?

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

问题描述

我是Java初学者,所以请忍受这个。

I'm a Java-beginner, so please bear with this one.

我有一个课程:

class Point {
  public int x;
  public int y;

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

我创建了两个实例:

Point a = new Point(1, 1);
Point b = new Point(1, 1);

我想检查这两个点是否在同一个地方。显而易见的是,如果(a == b){...} ,则不起作用,因为这似乎是是对象等于?一种测试,这不是我想要的。

I want to check if these two points are at the same place. The obvious way, if (a == b) { ... }, does not work since this seems to be an "are the objects equal?" kind of test, which is not what I want.

我能做 if((ax == bx)&&(ay = =))){...} ,但是这个解决方案感觉不太好。

I can do if ( (a.x == b.x) && (a.y == b.y) ) { ... }, but that solution does not feel good.

如何获取两个Point-objects并测试它们是否平等,以优雅的方式协调?

How can I take two Point-objects and test them for equality, coordinate wise, in an elegant way?

推荐答案

标准协议是实现 等于() 方法:

The standard protocol is to implement the equals() method:

class Point {
  ...
  @Override
  public boolean equals(Object obj) {
    if (!(obj instanceof Point)) return false;
    Point rhs = (Point)obj;
    return x == rhs.x && y == rhs.y;
}

然后你可以使用 a.equals(b)

请注意,一旦完成此操作,您还需要实现 hashCode() 方法。

Note that once you've done this, you also need to implement the hashCode() method.

对于像你这样的课程,我经常使用 Apache Commons Lang 的< a href =http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/builder/EqualsBuilder.html> EqualsBuilder HashCodeBuilder

For classes like yours, I often use Apache Commons Lang's EqualsBuilder and HashCodeBuilder:

class Point {
  ...

  @Override
  public boolean equals(Object obj) {
    return EqualsBuilder.reflectionEquals(this, obj);
  }

  @Override
  public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);
  }
}

这篇关于如何检查价值平等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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