猿问
回到首页
个人中心
反馈问题
注册登录
下载APP
首页
课程
实战
体系课
手记
专栏
慕课教程
在Java中覆盖equals和hashCode时应该考虑哪些问题?
什么问题/陷阱,必须重写时,必须考虑
equals
和
hashCode
?
在Java中覆盖equals和hashCode时应该考虑哪些问题?
凤凰求蛊
浏览 670
回答 3
3回答
人到中年有点甜
有关的澄清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() 也可以调用。
0
0
0
打开App,查看更多内容
随时随地看视频
慕课网APP
相关分类
Java
继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续