Java的可比接口(interface): Handling null arguments to compareTo()

标签 java exception null comparable

为框架扩展编写一些类,我有以下代码:

public class TimeImpl implements Time, Comparable<TimeImpl>, Serializable
{
...
    public int compareTo(TimeImpl other)
    {
        if (other == null)
            throw new ClassCastException("null");
        return Long.valueOf(toSeconds()).compareTo(other.toSeconds());
    }
}

如果你问我的话,实现非常简单。我的问题是:据我所知,Comparable 接口(interface)的 javadoc 没有提及任何关于 null 参数的信息。我应该费心检查一下吗?我应该更改抛出的异常类型吗?在这种情况下我应该返回其他值吗?其他人如何处理这个问题?

最佳答案

实际上,Comparable接口(interface)确实说了一些关于处理null参数的信息。

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.

关于Java的可比接口(interface): Handling null arguments to compareTo(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8935890/

相关文章:

python - 如何报告异常以备后用

java - 用户输入长度的异常处理

windows - C++/CX 捕获异常 - 如何打印完整堆栈?

c - C 中的链表搜索/插入

php - 在 PDO 查询的 where 子句中处理可能的空值

json - Moshi/Kotlin - 如何将 NULL JSON 字符串序列化为空字符串?

java - 不应用 Java 中运算符的优先级

java - 使用 Eclipse 远程调试 Tomcat - 忽略断点

java - 无法使用MAVEN命令

java - retrofit2 上没有这样的文件或目录调用响应