简体   繁体   English

Java的可比较接口:处理null参数以进行compareTo()

[英]Java's Comparable Interface: Handling null arguments to compareTo()

Writing some classes for a Framework extension, and I have the following code: 为Framework扩展编写一些类,我有以下代码:

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. 我的问题是:据我所知,Comparable接口的javadocs对于空参数没有说什么。 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? 那里的其他人如何处理呢?

I prefer to throw NullPointerException rather than ClassCastException . 我更喜欢抛出NullPointerException而不是ClassCastException

This convention is also followed by JDK implementations. JDK实现也遵循此约定。

Actually, the Comparable interface does say something about handling null arguments. 实际上, Comparable接口确实说明了有关处理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. 请注意,null不是任何类的实例,即使e.equals(null)返回false,e.compareTo(null)也应引发NullPointerException。

The code below is the compareTo method of Integer from java: 下面的代码是来自Java的Integer的compareTo方法:

 public int compareTo(Integer anotherInteger) 
 {
    int thisVal = this.value;
    int anotherVal = anotherInteger.value;
    return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
 }

why not implement your compareTo method in the way Integer does. 为什么不以Integer的方式实现compareTo方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM