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.
Personally, I like Guava’s
Orderingfor null-safe comparing. You can specify#nullsFirst()or#nullsLast()to avoidNullPointerExceptions.Other important notes, mostly from the comments:
thisis nevernullin JavaComparisonChainif you’re implementing a fine-grainedcompareTo()When implementing
Comparable, be sure to specify the type parameter so you get compile-time type safety and don’t have to useinstanceofor casts: