java—当对象o为null时,无法在equals()方法中返回false我已经添加了equals()实现以及测试用例

h4cxqtbf  于 2021-07-08  发布在  Java
关注(0)|答案(2)|浏览(214)

我的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());

}
pengsaosao

pengsaosao1#

首先,为了正确覆盖 Objectequals() ,方法签名应为:

public boolean equals(Object o) {
    ....
}

即使测试代码调用 equals() 方法,jdk类 Objectequals() 签名无效。
另外,你应该回来 false 当你发现 o 论点是 null ,以避免以后在方法中访问它(这将导致 NullPointerException ).
正确的实现可以如下所示:

public boolean equals (Object o) 
{
    if (this == o) {
        return true;
    }
    if (o == null || !(o instanceof Prof)) {
        return false; 
    }
    Prof other = (Prof) o;
    return this.year == other.year && this.id.equals(other.id);
}
cwdobuhd

cwdobuhd2#

在java中,对象类是每个类的超类。因此,为了覆盖对象类中定义的equal方法,您需要遵循相同的方法定义,即:

@Override
public boolean equals(Object other) {
   // here goes your implementation class
}

因为你对 equalsProf 作为参数,因此实际上并没有重写对象 equals 方法。
有关 equals 合同,你可以看 Item10Effective Java 预订人 Josh Bloch .
另外,如果类有equals方法,那么也应该始终定义hashcode实现。以下是此方法的实现:

@Override
 public int hashCode() {
     return Objects.hash(year, id);
 }

相关问题