public class ComparableExample implements Comparable<ComparableExample> { private int number; private boolean bool; private String str; private Object obj; @Override public boolean equals(Object o) { if (null == o) { return false; } if (this == o) { return true; } if ( ! (o instanceof ComparableExample) ) { return false; } return 0 == compareTo((ComparableExample)o); } public int compareTo(ComparableExample that) { final int BEFORE = -1; final int EQUAL = 0; final int AFTER = 1; if (null == that) { throw new NullPointerException(getClass().getSimpleName() + ".compareTo() called with a null parameter"); } if (this == that) { return EQUAL; } int result = EQUAL; if (EQUAL == result) { result = (this.number < that.number ? BEFORE : (this.number > that.number ? AFTER : EQUAL)); } if (EQUAL == result) { result = (this.bool ? (that.bool ? EQUAL : AFTER) : (that.bool ? BEFORE : EQUAL)); } if (EQUAL == result) { result = (null == this.str ? (null == that.str ? EQUAL : BEFORE) : this.str.compareTo(that.str)); } if (EQUAL == result) { result = (null == this.obj ? (null == that.obj ? EQUAL : BEFORE) : this.obj.compareTo(that.obj)); } return result; } }
Tuesday, June 29, 2010
Java Comparable and equals() implementation
It is strongly recommended (though not required) that the natural ordering of a class (compareTo() method) be consistent with the equals() method (see java.lang.Comparable). The best way to keep them consistent, is to implement the equals() method as a call to the compareTo() method. This will increase the maintainability of the code: if any new fields are added to the class in the future, they will only have to be added to the compareTo() method, the equals() method will not have to be changed. When calling compareTo() from equals(), we need to be careful, because e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment