Tuesday, 15 February 2011

java - hashCode and compareTo for non-standard equals -



java - hashCode and compareTo for non-standard equals -

given next implementation of equals:

public class test implements comparable<test> { private int x, y; @override public boolean equals(object obj) { if (obj instanceof test) { test other = (test) obj; homecoming x == other.x || y == other.y; } homecoming false; } @override public int hashcode() { //implementation? } @override public int compareto(test o) { //implementation? } }

what correct/most performant implementation of hashcode , compareto? please note - equals uses or, not and

equals() method used determine equality of 2 objects.

when equality, should adhere next properties,

reflexive: always, = a. in java, a.equals(a) should true.

symmetric: if = b, b = a. in java, if a.equals(b) true, b.equals(a) should true.

transitive: if = b , b = c, = c. in java, if a.equals(b) , b.equals(c) true, a.equals(c) should true.

your equals() doesnot face upwards rules.

moreover according javadoc - recommended (though not required) natural orderings consistent equals. because sorted sets (and sorted maps) without explicit comparators behave "strangely" when used elements (or keys) natural ordering inconsistent equals. may face problem using implementation of equals() while natural sorting

good approach overriding equals method in java

do check -- if yes homecoming true. do null check -- if yes homecoming false. do instanceof check type cast object compare individual attribute starting numeric attribute because comparing numeric attribute fast , utilize short circuit operator combining checks. if first field not match, don't seek match rest of attribute , homecoming false.

java

No comments:

Post a Comment