by irogers · 4y ago · 0 comments
public MyFile implements Comparable { ... long timestamp; ... @Override public int compare(Object other) { return (int)(((MyFile)other).timestamp - timestamp; } ... }
The int conversion loses the sign of the subtract. The particular use of the code was sorting files to delete the X number of oldest.
More examples about the dangers with just ints: https://stackoverflow.com/questions/2728793/java-integer-com...
The comparable API in Java came from the C qsort API. It would have been better to just have a less-than method. Kind of surprised to see this in Go near a core API.
For two values `x` and `y` of the same type with fields `a` and `b`, this lets you compare on `a` first and then on `b` by writing
``` x.a.cmp(&y.a).then(x.b.cmp(&y.b)) ```
(x.a, x.b) < (y.a, y.b)
btw you can format as code by indenting two spaces.Using -1, 0 and 1 to represent these feels like something that was a clever trick for low level code on a PDP-11 and hasn't been a good idea since the 1970s.
The reason to avoid subtraction is that you can get integer underflow if one operand is negative and one is positive, and then the result of Long.signum(b - a) is different from Long.compare(a, b).