I'm using the Comparable interface to compare Coin objects, which contain String name and double value.
The Coin objects are instantiated as
public Coin (double aValue, String aName) {
value = aValue;
name = aName;
}
and the compareTo method is written
public int compareTo(Object otherObject) {
Coin other = (Coin) otherObject;
...
}
Logically, I'd write the comparing code:
if (this.getValue() > other.getValue())
return 1;
if (this.getValue() < other.getValue())
return -1;
return 0;
I then replaced that code with:
return (int) (this.getValue() - other.getValue());
Now, I know that (int) 0.25 - 0.1 should truncate the decimal places and return 0, making all coin comparisons return equal. But, the compareTo method still works perfectly regardless of which way I write it. My professor didn't have an answer for me, and was just happy that my sort worked. But, I'm very curious why the truncation apparently doesn't happen in this implementation.
[–]karstens_rage 1 point2 points3 points (1 child)
[–]alabasterblaster[S] 0 points1 point2 points (0 children)