gpt4 book ai didi

java - 字符串比较

转载 作者:行者123 更新时间:2023-12-02 23:42:01 25 4
gpt4 key购买 nike

有人知道为什么 String.compareTo 没有被编程为对 null 参数表现得更友好吗?

在我看来,下一个序列应该返回“1”,或者至少 javadoc 对于 NPE 应该更加具体。在这种情况下,equals() 返回 false,我猜 equalscompareTo 应该是一致的。

例如

String nullString = null;
System.out.println ("test".equals(nullString));
System.out.println ("test".compareTo(nullString));

正在抛出 NPE:

false
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.compareTo(String.java:1177)

添加到它。如果您要在代码中进行此比较,您会验证空值吗?

最佳答案

因为它是documented behavior of compareTo() (强调):

The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C. 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.

至于.equals()返回false而不是NPEing,同样,它在the documentation中:

For any non-null reference value x, x.equals(null) should return false.

关于java - 字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11207739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com