Java: null safe compareTo method
comparator, compare, java
Solution
Personally, I like Guava's `Ordering` for null-safe comparing. You can specify `#nullsFirst()` or `#nullsLast()` to avoid `NullPointerException`s.
Other important notes, mostly from the comments:
- `this` is never `null` in Java
- Consider using Guava's `ComparisonChain` if you're implementing a fine-grained `compareTo()`
When implementing `Comparable`, be sure to specify the type parameter so you get compile-time type safety and don't have to use `instanceof` or casts:
class Tok implements Comparable<Tok> {
// snip
public int compareTo(Tok other) {
// snip
}
}
Problem
It has been asked before, but I have not found a decent implementation with an explanation. ``` public int compareTo(Object o) { if (this == null || o == null) { return 0; } Tok tmp = (Tok) o; if (this.rang < tmp.rang) { return -1; } else if (this.rang > tmp.rang ) { return 1; } else { return 0; } } ``` I read two similar questions that I found yet; they insist on implementing another method. I do not understand why this should not work. The method gets an extra object and it checks if its a valid instance or `null`, if `null` simply return `0`; what would be the easiest way to implement null-safe `compareTo`. The implementation that worked for me was: ``` public int compareTo(Object o) { if (o == null) { return 0; } Tok tmp = (Tok) o; if (this.rang < tmp.rang) { return -1; } else if (this.rang > tmp.rang ) { return 1; } else { return 0; } } ``` It's not the optimal implementation one should look in to what good people posted here as answers. For my particular case this was decent enough as this is never null yet the object received can be null and the initial implementation states if either is null return 0. So if given object is null 0 is returned.