Nice general way to sort nulls to the bottom, regardless?

后端 未结 5 561
北恋
北恋 2021-01-02 10:53

I\'m writing some custom Comparators, and I\'d like them to push null items to the bottom of the list, regardless of whether I\'m sorting ascending or descending. What\'s a

5条回答
  •  灰色年华
    2021-01-02 11:45

    The last option appeals to me a lot. Comparators are really great to chain together. In particular you may well want to write a ReverseComparator as well as a NullWrappingComparator.


    EDIT: You don't have to write this yourself. If you look at the Ordering class in the Google Collections Library you'll find this and all kinds of other goodies :)


    EDIT: Going into more detail to show what I mean about ReverseComparator...

    One word of warning - in the implementation of a ReverseComparator, reverse the order of the arguments instead of negating the result, as otherwise Integer.MIN_VALUE is "reversed" to itself.

    So this implementation is wrong (assuming original is the comparator to reverse):

    public int compare(T x, T y)
    {
        return -original.compare(x, y);
    }
    

    but this is right:

    public int compare(T x, T y)
    {
        return original.compare(y, x);
    }
    

    The reason is that we always want to reverse the comparison, but if original.compare(x, y) returns int.MIN_VALUE, then the bad comparer will also return int.MIN_VALUE, which is incorrect. This is due to the funny property that int.MIN_VALUE == -int.MIN_VALUE.

提交回复
热议问题