Comparable and Comparator contract with regards to null

后端 未结 3 1839
刺人心
刺人心 2020-11-29 09:58

Comparable contract specifies that e.compareTo(null) must throw NullPointerException.

From the API:

Not

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 10:26

    Is it ever a good idea to even have to sort a List containing null elements, or is that a sure sign of a design error?

    Well, it probably doesn't make sense for the list to contain a null Object, but maybe your List contains a "business object" and you can sort on different properties of the business object, some of which may contain nulls.

    Is this an acceptable use of a Comparator

    The BeanComparator allows you to sort on a propery in a business object even if the property contains null, so I would have to say it is an acceptable use of a Comparator.

提交回复
热议问题