Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: null safe compareTo method

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.

like image 260
Sterling Duchess Avatar asked Nov 22 '12 17:11

Sterling Duchess


2 Answers

Personally, I like Guava's Ordering for null-safe comparing. You can specify #nullsFirst() or #nullsLast() to avoid NullPointerExceptions.

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
        }
    }
    
like image 103
Matt Ball Avatar answered Oct 24 '22 08:10

Matt Ball


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.

like image 33
EMMERICH Avatar answered Oct 24 '22 06:10

EMMERICH