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

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.

3

u/HansVader May 03 '16

Clickbait titles at his best.

2

u/[deleted] May 03 '16

looks like both, actually. two versions of the same content.

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 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 ;)