Comparable and Comparator contract with regards to null

后端 未结 3 1841
刺人心
刺人心 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

    Comparable doesn't allow null simply because:

    a.compareTo(b) == -b.compareTo(a)
    

    for all objects a and b where !a.equals(b). More specifically:

    a.equals(b) ? b.equals(a) && a.compareTo(b) == 0 &&
                      b.compareTo(a) == 0 && a.hashCode() == b.hashCode()
                : !b.equals(a) && a.compareTo(b) != 0 &&
                      a.compareTo(b) == -b.compareTo(a)
    

    must evaluate to true to satisfy the relevant contracts.

    So null isn't allowed because you can't do:

    null.compareTo(a)
    

    Comparator is more flexible so handling of null is an implementation-specific issue. Support it or not depending on what you want your Comparator to do.

提交回复
热议问题