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

Nze*_*zed 0 java oop junit compilation

我的 equals() 方法:例如,当我的对象为 null 时,在第二个 if 语句中,我应该返回 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;   
}
Run Code Online (Sandbox Code Playgroud)

测试用例:

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());
    
}
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 5

首先,为了正确覆盖Object's equals(),方法签名应该是:

public boolean equals(Object o) {
    ....
}
Run Code Online (Sandbox Code Playgroud)

即使您的测试代码调用您的equals()方法,期望Objectequals()签名的JDK 类也不会。

此外,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);
}
Run Code Online (Sandbox Code Playgroud)