为了账号安全,请及时绑定邮箱和手机立即绑定

在Java中覆盖equals和hashCode时应该考虑哪些问题?

在Java中覆盖equals和hashCode时应该考虑哪些问题?

凤凰求蛊 2019-05-21 14:59:41
什么问题/陷阱,必须重写时,必须考虑equals和hashCode?在Java中覆盖equals和hashCode时应该考虑哪些问题?
查看完整描述

3 回答

?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

有关的澄清obj.getClass() != getClass()。


这句话是equals()继承不友好的结果。该JLS(Java语言规范)规定,如果A.equals(B) == true那么B.equals(A)也必须返回true。如果省略该语句,则继承覆盖equals()(并更改其行为)的类将破坏此规范。


请考虑以下示例,省略语句时会发生什么:


    class A {

      int field1;


      A(int field1) {

        this.field1 = field1;

      }


      public boolean equals(Object other) {

        return (other != null && other instanceof A && ((A) other).field1 == field1);

      }

    }


    class B extends A {

        int field2;


        B(int field1, int field2) {

            super(field1);

            this.field2 = field2;

        }


        public boolean equals(Object other) {

            return (other != null && other instanceof B && ((B)other).field2 == field2 && super.equals(other));

        }

    }    

这样做new A(1).equals(new A(1))同时,new B(1,1).equals(new B(1,1))导致发出真实的,因为它应该。


这看起来非常好,但看看如果我们尝试使用这两个类会发生什么:


A a = new A(1);

B b = new B(1,1);

a.equals(b) == true;

b.equals(a) == false;

显然,这是错误的。


如果要确保对称条件。a = b如果b = a且Liskov替换原则super.equals(other)不仅在B实例的情况下调用,而且A例如在之后检查:


if (other instanceof B )

   return (other != null && ((B)other).field2 == field2 && super.equals(other)); 

if (other instanceof A) return super.equals(other); 

   else return false;

哪个会输出:


a.equals(b) == true;

b.equals(a) == true;

在哪里,如果a不是引用B,那么它可能是一个类的引用A(因为你扩展它),在这种情况下你super.equals() 也可以调用。


查看完整回答
反对 回复 2019-05-21
  • 3 回答
  • 0 关注
  • 669 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号