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 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 JavaComparisonChain
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
}
}
Returning 0 would imply that this
and o
are equal, which isn't true if o
is null. Also, this
will never be null.
It's application-dependent, of course. You may want to have an object that should be equal to null. What you return there is up to you, but if you're looking for a general null safe method, it isn't really ideal.
To be completely generic, I would check if o
is null
and, if so, throw some sort of Exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With