views:

65

answers:

2

Hi,

When using Collection.sort in Java what should I return when one of the inner objects is null

Example:

Collections.sort(list, new Comparator<MyBean>() {
    public int compare(MyBean o1, MyBean o2) {
      return o2.getDate().compareTo(o1.getDate());
     } 

});

Lets say o2 is not null but o2.getDate() it is, so should I return 1 or -1 or 0 when adding a null validation?

+1  A: 

Naturally, it's your choice. Whatever logic you write, it will define sorting rules. So 'should' isn't really the right word here.

If you want null to appear before any other element, something like this could do

public int compare(MyBean o1, MyBean o2) {
    if (o1.getDate() == null) {
        return (o2.getDate() == null) ? 0 : -1;
    }
    if (o2.getDate() == null) {
        return 1;
    }
    return o2.getDate().compareTo(o1.getDate());
} 
Nikita Rybak
+1  A: 

It depends, do you consider null as a big value or a low value.

You can consider most of the time that null < everything else, but it depends on the context.

And 0 would be a terrible return value here.

Colin Hebert