Comparable and Comparator contract with regards to null

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

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

From the API:

Not

3条回答
  •  一整个雨季
    2020-11-29 10:42

    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?

    Conceptually, null means "nothing", and placing nothing in a list seems weird to me. Also, the Java List contract states that

    Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements

    so a List implementation in Java is not even required to support null elements at all. To sum up, if you do not have a good reason to put null into a list, don't, and if you do, test that it actually works as expected.

提交回复
热议问题