容易忽略的equals顺序问题

我们在用equals时常常不注意这个问题,a.equals(b)和b.equals(a)能一样么?答案是不一样!因此用的时候多注意不同的顺序,我也看到过说用getClass的,我不同意这种用法,毕竟getClass就屏蔽了好多子类。

public class EqualsDemo {
  public static void main(String[] args) {
    Father father = new Father("HS");
    Son son1 = new Son(1001, "HS");
    Son son2 = new Son(1002, "HS");
    System.out.println(son1.equals(son2));
    System.out.println(son1.equals(father));
    System.out.println(son2.equals(father));
    System.out.println(father.equals(son1));
  }
}

class Father {
  private String name;

  public Father(String name) {
    this.name = name;
  }

  @Override
  public boolean equals(Object obj) {
    if (obj instanceof Father) {
      Father that = (Father) obj;
      return this.name.equals(that.name);
    }
    return false;
  }
}

class Son extends Father {
  private int id;

  public Son(int id, String name) {
    super(name);
    this.id = id;
  }

  @Override
  public boolean equals(Object obj) {
    if (obj instanceof Son) {
      Son that = (Son) obj;
      return this.id == that.id && super.equals(that);
    }
    return false;
  }
}
1001
false
false
false
true

转载于:https://my.oschina.net/xd03122049/blog/866637

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值