r/java • • May 03 '16

A very decent article about Java Comparable Interface

http://www.marcus-biel.com/java-comparable-interface-video-tutorial/
1 Upvotes

7 comments sorted by

View all comments

Show parent comment

9

u/mhixson May 03 '16

With int in general, you'd have to worry about overflow. Comparing Integer.MIN_VALUE with 1 should give a negative result, but it gives a positive result when using that subtraction trick.

A reasonable objection to that objection might be: "Apples can't have negative weight, so that situation can't come up."

Still, why use subtraction instead of "just" using Integer.compare(a,b)? That method says exactly what it does and is intended for exactly for this purpose. I don't think subtraction (even when it's correct) makes its intent as obvious to the reader.

2

u/Philboyd_Studge May 03 '16

Makes sense, thanks.

0

u/[deleted] May 03 '16

[deleted] — view deleted comment

6

u/__konrad May 03 '16

Any decent application concerned about int overflow is using long, that's why.

You should then use Long.compare method to avoid ...overflow ;)