Issue
My equals() method: Here when in second if statement when my my object is null for example, I should return false but for some reason my code fails to do so. Any help?
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;
}
Test Case:
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());
}
Solution
In Java Object class is the superclass of every class. So in order to override the equal method defined in the Object class, you need to follow the same method definition, which is:
@Override
public boolean equals(Object other) {
// here goes your implementation class
}
Since your definition of equals
has Prof
as an argument, hence you are not actually overriding the Object equals
method.
For more information on the equals
contract, you can read Item10
from Effective Java
book by Josh Bloch
.
Also, if your class has an equals method, then you should always define the hashCode implementation as well. Here is the implementation of this method:
@Override
public int hashCode() {
return Objects.hash(year, id);
}
Answered By - Rohan Sharma