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?
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.
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
Following the answer from Nikita Rybak, i'm already have a enum comparator, and only add the null logic from here.
In this form i can call the sort method on my list.
In Java 8 you can also use
nullsFirst()
:Or
nullsLast()
:These methods will either sort
null
to the beginning or to the end. There is no wrong or right whether you considernull
bigger or smaller than another objects. This is totally up to you, as others stated already.