Question

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?

Was it helpful?

Solution

You should definitely not write compareTo methods like this:

  • It will fail if you have this.data = 0.5f and object.data = 0.2f for example - presumably that should return a positive value, but it will return 0
  • It could overflow the range of int (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)
  • For similar situations with int, you can end up subtracting a positive number from a negative number and getting a large positive number due to overflow

I'm sure I could think of other nasty situations with enough effort.

Fortunately, the fix is easy:

return Float.compare(this.data, object.data);

OTHER TIPS

Unless you have a very good reason, I would use double instead of float to minimise representation error (by a factor of 9 digits!) In an object, using float might not even save any memory.

As such I would use which works whether you use a float or a double or an int for that matter.

public int compareTo(SomeObj object) {
   return Double.compare(data, object.data);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top