问题描述
在Java中测试 String
的相等性时,我总是使用 equals()
因为对我这个似乎是最自然的方法。毕竟,它的名字已经说明了它的目的。然而,我最近告诉我的一位同事被教导使用 compareTo()== 0
而不是 equals()
。这感觉不自然(因为 compareTo()
意味着提供排序而不是比较相等)甚至有些危险(因为 compareTo()== 0
并不一定意味着在所有情况下都是平等的,即使我知道它对我来说也是 String
'。
When testing for equality of String
's in Java I have always used equals()
because to me this seems to be the most natural method for it. After all, its name already says what it is intended to do. However, a colleague of mine recently told me had been taught to use compareTo() == 0
instead of equals()
. This feels unnatural (as compareTo()
is meant to provide an ordering and not compare for equality) and even somewhat dangerous (because compareTo() == 0
does not necessarily imply equality in all cases, even though I know it does for String
's) to me.
他不知道为什么他被教导使用 compareTo()
而不是 equals()
for String
,我也找不到任何理由。这真的是个人品味的问题,还是有任何方法的真正原因?
He did not know why he was taught to use compareTo()
instead of equals()
for String
's, and I could also not find any reason why. Is this really a matter of personal taste, or is there any real reason for either method?
推荐答案
区别在于foo.equals((String)null)
返回false,而foo.compareTo((String)null)== 0
抛出NullPointerException。因此,即使对于Strings,它们也不总是可以互换的。
A difference is that "foo".equals((String)null)
returns false while "foo".compareTo((String)null) == 0
throws a NullPointerException. So they are not always interchangeable even for Strings.
这篇关于Java字符串:compareTo()与equals()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!