我的equals()方法:例如,在第二个if语句中,当我的对象为null时,我应该返回false,但由于某些原因,我的代码没有这样做。有什么帮助吗?
public boolean equals(Prof o) {
boolean res = false;
if(this == o) {
res = true;
}
if(o == null || this.getClass() != o.getClass()) {
res = false;
}
Prof other = (Prof) o;
if(this.year == other.year) {
if(this.id.equals(other.id)) {
res = true;
}
}
else {
res = false;
}
return res;
}
测试用例:
public void test02_ProfEqualHash() {
Prof p1 = new Prof("John S Lee", "yu213", 5);
assertTrue(p1.equals(p1));
Prof p0 = null; // null
assertFalse(p1.equals(p0)); // my equals() implementation fails here
Date d = new Date();
String s = "Hello";
assertFalse(p1.equals(d));
assertFalse(p1.equals(s));
Prof p2 = new Prof("John L", "yu213", 5);
assertTrue(p1.equals(p2));
assertTrue(p1.hashCode() == p2.hashCode());
assertTrue(p2.equals(p1));
Prof p3 = new Prof("John S Lee", "yu203", 5);
assertFalse(p1.equals(p3));
//assertNotEquals(p1.hashCode(), p3.hashCode());
Prof p4 = new Prof("Tracy T", "yu053", 2);
assertFalse(p1.equals(p4));
//assertNotEquals(p1.hashCode(), p4.hashCode());
Prof p5 = new Prof("John S Lee", "yu213", 8);
assertFalse(p1.equals(p5));
//assertTrue(p1.hashCode() != p5.hashCode());
}
2条答案
按热度按时间pengsaosao1#
首先,为了正确覆盖
Object
的equals()
,方法签名应为:即使测试代码调用
equals()
方法,jdk类Object
的equals()
签名无效。另外,你应该回来
false
当你发现o
论点是null
,以避免以后在方法中访问它(这将导致NullPointerException
).正确的实现可以如下所示:
cwdobuhd2#
在java中,对象类是每个类的超类。因此,为了覆盖对象类中定义的equal方法,您需要遵循相同的方法定义,即:
因为你对
equals
有Prof
作为参数,因此实际上并没有重写对象equals
方法。有关
equals
合同,你可以看Item10
从Effective Java
预订人Josh Bloch
.另外,如果类有equals方法,那么也应该始终定义hashcode实现。以下是此方法的实现: