How to simplify a null-safe compareTo() implementation?

前端 未结 17 2111
醉酒成梦
醉酒成梦 2020-11-28 18:03

I\'m implementing compareTo() method for a simple class such as this (to be able to use Collections.sort() and other goodies offered by the Java pl

17条回答
  •  囚心锁ツ
    2020-11-28 18:30

    I know that it may be not directly answer to your question, because you said that null values have to be supported.

    But I just want to note that supporting nulls in compareTo is not in line with compareTo contract described in official javadocs for Comparable:

    Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.

    So I would either throw NullPointerException explicitly or just let it be thrown first time when null argument is being dereferenced.

提交回复
热议问题