未记载的String.compareTo(null)NPE? [英] Undocumented String.compareTo(null) NPE?

查看:157
本文介绍了未记载的String.compareTo(null)NPE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下小测试会抛出NPE:

The following little test throws an NPE:

public class Test {

    public static void  main(String[] args) {

        String a = "a";
        String b = null;

        System.out.println(a.compareTo(b));

    }

}

然而, compareTo()没有提到参数不能 null 。这很奇怪,因为Javadocs通常会提到参数不能 null

Yet, the Javadoc of compareTo() does not mention that the parameter cannot be null. This is strange, since Javadocs usually mentions when parameters cannot be null.

这只是文档中的一个小故障还是有一个更基本的原因/扭曲我错过了?

Is this just a glitch in the documentation or is there a more fundamental reason/twist I am missing?

推荐答案

当你看到可比较界面:


请注意,null不是任何类的实例,并且e.compareTo(null)
应抛出NullPointerException,即使e.equals(null)返回
false。

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.

这篇关于未记载的String.compareTo(null)NPE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆