Java compareTo() 与 equals()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1551235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
compareTo() vs. equals()
提问by Thomas L?tzer
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.
String
在 Java 中测试's 的相等性时,我一直使用,equals()
因为对我来说这似乎是最自然的方法。毕竟,它的名字已经说明了它的意图。然而,我的一个同事最近告诉我已经被教导使用compareTo() == 0
代替equals()
。这感觉不自然(因为compareTo()
它旨在提供排序而不是比较相等性),甚至有点危险(因为compareTo() == 0
并不一定意味着在所有情况下都相等,即使我知道它对String
's 来说是这样)。
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?
他不知道为什么他被教导使用compareTo()
代替equals()
for String
's,我也找不到任何原因。这真的是个人品味的问题,还是这两种方法都有真正的原因?
采纳答案by waxwing
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.
不同之处在于"foo".equals((String)null)
在"foo".compareTo((String)null) == 0
抛出 NullPointerException 时返回 false 。因此,即使对于字符串,它们也不总是可以互换的。
回答by Scott M.
It appears that both methods pretty much do the same thing, but the compareTo() method takes in a String, not an Object, and adds some extra functionality on top of the normal equals() method. If all you care about is equality, then the equals() method is the best choice, simply because it makes more sense to the next programmer that takes a look at your code. The time difference between the two different functions shouldn't matter unless you're looping over some huge amount of items. The compareTo() is really useful when you need to know the order of Strings in a collection or when you need to know the difference in length between strings that start with the same sequence of characters.
看起来这两种方法几乎都做同样的事情,但是 compareTo() 方法接受一个字符串,而不是一个对象,并在普通的 equals() 方法之上添加了一些额外的功能。如果您只关心相等性,那么 equals() 方法是最佳选择,因为它对下一个查看您的代码的程序员更有意义。除非您要循环处理大量项目,否则两个不同函数之间的时间差应该无关紧要。当您需要知道集合中字符串的顺序或需要知道以相同字符序列开头的字符串之间的长度差异时,compareTo() 非常有用。
source: http://java.sun.com/javase/6/docs/api/java/lang/String.html
来源:http: //java.sun.com/javase/6/docs/api/java/lang/String.html
回答by Kaleb Brasee
The 2 main differences are that:
两个主要区别是:
equals
will take any Object as a parameter, butcompareTo
will only take Strings.equals
only tells you whether they're equal or not, butcompareTo
gives information on how the Strings compare lexicographically.
equals
将接受任何对象作为参数,但compareTo
只会接受字符串。equals
只告诉您它们是否相等,但compareTo
提供有关字符串如何按字典顺序比较的信息。
I took a look at the String class code, and the algorithm within compareTo and equals looks basically the same. I believe his opinion was just a matter of taste, and I agree with you -- if all you need to know is the equality of the Strings and not which one comes first lexicographically, then I would use equals
.
我看了一下String类的代码,compareTo和equals里面的算法看起来基本一样。我相信他的意见只是一个品味问题,我同意你的看法——如果你只需要知道字符串的相等性,而不是按字典顺序排在第一位,那么我会使用equals
.
回答by starblue
When comparing for equality you should use equals()
, because it expresses your intent in a clear way.
在比较相等性时,您应该使用equals()
,因为它以清晰的方式表达了您的意图。
compareTo()
has the additional drawback that it only works on objects that implement the Comparable
interface.
compareTo()
有一个额外的缺点,它只适用于实现Comparable
接口的对象。
This applies in general, not only for Strings.
这适用于一般情况,不仅适用于字符串。
回答by robinr
compareTo
has do do more work if the strings have different lengths. equals
can just return false, while compareTo
must always examine enough characters to find the sorting order.
compareTo
如果字符串的长度不同,则需要做更多的工作。equals
可以只返回 false,而compareTo
必须始终检查足够的字符以找到排序顺序。
回答by apurva jadhav
compareTo()
not only applies to Strings but also any other object because compareTo<T>
takes a generic argument T
. String is one of the classes that has implemented the compareTo()
method by implementing the Comparable
interface.(compareTo() is a method fo the comparable Interface).So any class is free to implement the Comparable interface.
compareTo()
不仅适用于字符串,也适用于任何其他对象,因为compareTo<T>
它采用通用参数T
。String 是compareTo()
通过实现Comparable
接口来实现方法的类之一。(compareTo() 是可比较接口的一种方法)。所以任何类都可以自由地实现 Comparable 接口。
But compareTo()
gives the ordering of objects, used typically in sorting objects in ascending or descending order while equals()
will only talk about the equalityand say whether they are equal or not.
但是compareTo()
给出对象的排序,通常用于按升序或降序对对象进行排序,而equals()
只会谈论相等性并说明它们是否相等。
回答by Danubian Sailor
String.equals()
requires invoking instanceof
operator while compareTo()
requires not. My colleague has noted large performance drop-down caused by excessive numbers of instanceof
calls in equals()
method, however my test has proved compareTo()
to be only slightly faster.
String.equals()
需要调用instanceof
运算符而不compareTo()
需要。我的同事注意到由于方法中的instanceof
调用次数过多而导致性能下降很大equals()
,但是我的测试证明compareTo()
只是稍微快了一点。
I was using, however, Java 1.6. On other versions (or other JDK vendors) the difference could be larger.
但是,我使用的是 Java 1.6。在其他版本(或其他 JDK 供应商)上,差异可能更大。
The test compared each-to-each string in 1000 element arrays, repeated 10 times.
该测试比较了 1000 个元素数组中的每个字符串,重复 10 次。
回答by Seema Kiran
There are certain things which you need to keep in mind while overriding compareTo in Java e.g. Compareto must be consistent with equals and subtraction should not be used for comparing integer fields as they can overflow. check Things to remember while overriding Comparator in Javafor details.
在 Java 中覆盖 compareTo 时需要记住某些事情,例如,Compareto 必须与等于一致,并且不应该使用减法来比较整数字段,因为它们可能会溢出。查看在 Java 中重写 Comparator 时要记住的事情以获取详细信息。
回答by littletiger
equals
can take any Object as a parameter butcompareTo
can only take String.when cometo null,
compareTo
will throw a exceptionwhen you want to know where the diff happen,you can use
compareTo
.
equals
可以接受任何对象作为参数,但compareTo
只能接受字符串。当归零时,
compareTo
会抛出异常当您想知道差异发生在哪里时,您可以使用
compareTo
.
回答by VirtualLogic
In String Context:
compareTo: Compares two strings lexicographically.
equals: Compares this string to the specified object.
在字符串上下文中:
compareTo:按字典顺序比较两个字符串。
等于:将此字符串与指定的对象进行比较。
compareTo compares two strings by their characters (at same index) and returns an integer (positive or negative) accordingly.
compareTo 按字符(在同一索引处)比较两个字符串,并相应地返回一个整数(正数或负数)。
String s1 = "ab";
String s2 = "ab";
String s3 = "qb";
s1.compareTo(s2); // is 0
s1.compareTo(s3); // is -16
s3.compareTo(s1); // is 16