I'm fairly new to java and am just trying to get my head around understanding @Override
of the equals()
and hashcode()
methods.
I know for the equals method to be correct it needs to be:
- Reflexive:
a.equals(a)
- Symmetric:
a.equals(b)
thenb.equals(a)
- Transitive:
a.equals(b) && b.equals(c)
Thena.equals(c)
- Not null:
! a.equals(null)
I am struggling to pinpoint which of the above properties I am and am not satisfying when writing my overide of the equals method.
I am aware that eclipse can generate these for me, however as I haven't yet gotten the concept fully, writing it out helps me to learn.
I have written out the what I think is the correct way to do it, but when I check with the eclipse generated version I seem to be 'missing' some aspects.
Example:
public class People {
private Name first; //Invariants --> !Null, !=last
private Name last; // !Null, !=first
private int age; // !Null, ! <=0
...
}
What I wrote:
public boolean equals(Object obj){
if (obj == null){
return false;
}
if (!(obj instanceof People)){
return false;
}
People other = (People) obj;
if (this.age != other.age){
return false;
}
if (! this.first.equals(other.first)){
return false;
}
if (! this.last.equals(other.last)){
return false;
}
return true;
}
vs eclipse generated
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
People other = (People) obj;
if (first == null) {
if (other.first != null)
return false;
} else if (!first.equals(other.first))
return false;
if (age != other.age)
return false;
if (last == null) {
if (other.last != null)
return false;
} else if (!last.equals(other.last))
return false;
return true;
}
I am missing:
if (this == obj) return true;
if (getClass() != obj.getClass()) return false;
And for each variable:
if (first == null) { if (other.first != null) return false; } else if (!first.equals(other.first)) return false;
I'm not sure what getClass()
is and is my implmentation incorrect?