How to handle nulls when using Java collection sort

后端 未结 6 2066
离开以前
离开以前 2020-12-29 19:39

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

Example:

Collections.sort(list, new Comparator

        
6条回答
  •  一生所求
    2020-12-29 20:30

    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());
    } 
    

提交回复
热议问题