关于对象比较

时间:2010-02-23 02:55:24

标签: java class

我正在使用java类Rec。我有两个实例Rec1和Rec2。我想检查Rec1和Rec2的值是否相等。如果我做Rec1.equals(Rec2)这是正确的做法吗?

class Rec {

  private BigDecimal  RecordId = null; 

  private BigDecimal recSubNum = null; 

  private BigDecimal  FileId = null;

  private String    Category = null; 

  private BigDecimal status = null; 

  private BigDecimal errorCode = null; 

} 

2 个答案:

答案 0 :(得分:3)

您需要实现equals()hashCode()方法以在Java中实现对象相等性:

class Rec {
  private BigDecimal recordId = null;
  private BigDecimal recSubNum = null;
  private BigDecimal FileId = null;
  private String category = null;
  private BigDecimal status = null;
  private BigDecimal errorCode = null;

  @Override
  public int hashCode() {
    int ret = 41;
    ret = hc(ret, recordId);
    ret = hc(ret, recSubNum);
    ret = hc(ret, fieldId);
    ret = hc(ret, category);
    ret = hc(ret, status);
    ret = hc(ret, errorCode);
    return ret;
  }

  @Override
  public boolean equals(Object ob) {
    if (ob == null) return false;
    if (ob.getClass() != Rec.class) return false;
    Rec r = (Rec)ob;
    if (!eq(r.recordId, record)) return false;
    if (!eq(r.recSubNum, recSubNum)) return false;
    if (!eq(r.fileId, fileId)) return false;
    if (!eq(r.category, category)) return false;
    if (!eq(r.status, status)) return false;
    if (!eq(r.errorCode, errorCode)) return false;
    return true;
  }

  private static boolean eq(Object ob1, Object ob2) {
    return ob1 == null ? ob2 == null : ob1.equals(ob2);
  }

  private static int hc(int hc, Object field) {
    return field == null ? hc : 43 + hc * field.hashCode();
  }
}

注意: Java的equals / hashCode合约意味着对于任何两个对象a和b:

a.equals(b) == b.equals(a)

如果两个对象相等,那么a.hashCode()必须等于b.hashCode()

编辑:有两种方法可以检查类型是否匹配。之一:

if (ob == null) return false;
if (ob.getClass() != Rec.class) return false;

if (!(ob instanceof Rec)) return false;

这两个做不同的事情,你应该根据你想做的事情选择正确的。我通常更喜欢第一个,除非你知道你需要第二个。有什么区别?

class A {
  public int i;

  public boolean equals(Object ob) {
    if (!(ob instanceof A)) return false;
    return i == ((A)ob).i;
  }
}

看起来合理吗?如果课程被扩展怎么办:

class B extends A {
  public int j;

  public boolean equals(Object ob) {
    if (!(ob instanceof B)) return false;
    if (!super.equals(ob)) return false;
    return j == ((B)ob).j;
  }
}

看起来还算合理吗?它坏了。

A a = new A();
a.i = 10;
B b = new B();
b.i = 10;
b.j = 20;
System.out.println(a.equals(b)); // true! Is this really what you want?
System.out.println(b.equals(a)); // false! Different to previous = problem.

这就是为什么我赞成getClass()超过instanceof,除非我确实希望子类相等。

答案 1 :(得分:0)

如果Rec是用户定义的类,那么你真的应该重写equals方法,否则它只会调用Object类中的equals方法;

类似的东西:

public boolean equals(Rec x){
    //check here to see if the references are the same, if so return true
    if(this == x) return true;

    //if they aren't the same object then check all the fields for equality
    if (category.equals(x.category) && etc etc) return true;
    else return false;
}