`Comparable::compareTo` 的最简单实现

Simplest implementation of `Comparable::compareTo`

对于 StockQuote class 实施 Comparable< StockQuote > with a when property of type LocalDateTime

public class StockQuote implements Comparable< StockQuote >
{
    private LocalDateTime when;
    …
}

Comparable::compareTo 的以下实现是否足够?

@Override
public int compareTo ( StockQuote that )
{
    return this == that ? 0 : this.getWhen().compareTo( that.getWhen() );
}

首先使用 this == that 检查对象标识,声明相等:

如果相同,则此代码将that转换为预期类型,并从两者中提取when对象。然后我们return调用内置LocalDateTime::compareTo方法的结果。如果 thisthat 为空,但不是两者都为空,则抛出 NullPointerException

我想知道如何使用 Objects.compareTo or Comparator.comparing

Per the Java APIcompareTo 如果其参数为 null,则应抛出 NullPointerException

Throws: NullPointerException - if the specified object is null

== 检查是允许的优化,但不是必需的。您可以推迟到 LocalDate.compareTo() 并结束它:

return this.getWhen().compareTo( that.getWhen() );

您也可以放弃 getter 并直接访问 .when

return this.when.compareTo( that.when );