为框架扩展编写一些类,我有以下代码:
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/