Java 的可比较接口:处理compareTo() 的空参数
为框架扩展编写一些类,我有以下代码:
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 接口的 javadoc 没有提及任何关于 null 参数的信息。我应该费心检查一下吗?我应该更改抛出的异常类型吗?在这种情况下我应该返回其他值吗?那里的其他人如何处理这个问题?
Writing some classes for a Framework extension, and I have the following code:
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());
}
}
Pretty straightforward implementation, if you ask me. My question is: as far as I can tell, the javadocs for the Comparable interface say nothing regarding null arguments. Should I bother checking for it? Should I change the type of exception thrown, should I return some other value in that case? How are other people out there handling this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实际上,
Comparable
接口确实说了一些关于处理null
参数的信息。Actually, the
Comparable
interface does say something about handlingnull
arguments.我更喜欢抛出 NullPointerException 而不是 ClassCastException。
JDK 实现也遵循此约定。
I prefer to throw
NullPointerException
rather thanClassCastException
.This convention is also followed by JDK implementations.
下面的代码是java中Integer的compareTo方法:
为什么不以Integer的方式实现compareTo方法呢?
The code below is the compareTo method of Integer from java:
why not implement your compareTo method in the way Integer does.