Is there a potential for overflow if I were to write the following:
public class SomeObj implements Comparable<SomeObj> {
private final float data;
public SomeObj(float data) {
this.data = data;
}
public int compareTo(SomeObj object) {
return (int) (this.data - object.data);
}
}
I’ve seen other Java developers write their compareTo methods like how I did above as a shortcut instead of writing a bunch of if-else statements. Would the latter be the best approach to implementing the compareTo method here if there really is a potential for overflow?
You should definitely not write
compareTomethods like this:this.data = 0.5fandobject.data = 0.2ffor example – presumably that should return a positive value, but it will return 0int(I can’t even remember what Java does in that case, offhand – casting in such a situation is almost always the wrong approach, so I don’t usually need to remember)int, you can end up subtracting a positive number from a negative number and getting a large positive number due to overflowI’m sure I could think of other nasty situations with enough effort.
Fortunately, the fix is easy: