java - Which part of the equals() general contract does my equals() not satisfy -
i'm new java , trying head around understanding @override
of equals()
, hashcode()
methods.
know equals method correct needs 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 struggling pinpoint of above properties , not satisfying when writing overide of equals method.
i aware eclipse can generate these me, haven't yet gotten concept fully, writing out helps me learn.
i have written out think correct way it, when check eclipse generated version seem 'missing' aspects.
example:
public class people { private name first; //invariants --> !null, !=last private name last; // !null, !=first private int age; // !null, ! <=0 ... }
what 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 missing:
if (this == obj) return true;
if (getclass() != obj.getclass()) return false;
and each variable:
if (first == null) { if (other.first != null) return false; } else if (!first.equals(other.first)) return false;
i'm not sure getclass()
, implmentation incorrect?
first piece of code:
if (this == obj) return true;
this improves performance in case compare object reference against itself. example: a.equals(a);
.
second piece of code:
if (getclass() != obj.getclass()) return false;
this compares if class of reference being compared same class of this
. difference between using approach , instanceof
it's more restrictive when comparing against sub class. example:
public class foo { } public class bar extends foo { } //... foo foo = new bar(); system.out.println(foo instanceof bar); //prints true system.out.println(foo instanceof foo); //prints true foo foo2 = new foo(); system.out.println(foo.getclass() == foo2.getclass()); //prints false
which 1 should choose? there's no or bad approach, depend on desired design.
third piece of code:
if (first == null) { if (other.first != null) return false; } else if (!first.equals(other.first)) return false; //for each variable.
this null check each object reference field in class. note if this.first
null
doing this.first.equals(...)
throw nullpointerexception
.
Comments
Post a Comment