问题描述
在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()
来使用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.因此,即使对于字符串,它们也不总是可以互换的.
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.
这篇关于compareTo()与equals()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!