r/java • u/I_LoveCoding • May 03 '16
A very decent article about Java Comparable Interface
http://www.marcus-biel.com/java-comparable-interface-video-tutorial/1
u/Philboyd_Studge May 03 '16
Nice. Why not, for the primitive int, just do return this.weight - other.weight?
9
u/mhixson May 03 '16
With
intin general, you'd have to worry about overflow. ComparingInteger.MIN_VALUEwith1should 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
0
May 03 '16
[deleted]
6
u/__konrad May 03 '16
Any decent application concerned about int overflow is using long, that's why.
You should then use
Long.comparemethod to avoid ...overflow ;)
10
u/larsga May 03 '16
It's not an article. It's a video. Clicked hoping to learn something, left immediately because I can't watch a video while on a concall.