Java compare() 和 compareTo() 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/420223/
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
What is the difference between compare() and compareTo()?
提问by
What is the difference between Java's compare()
and compareTo()
methods? Do those methods give same answer?
Java的compare()
和compareTo()
方法有什么区别?这些方法给出相同的答案吗?
采纳答案by VonC
From JavaNotes:
a.compareTo(b)
:
Comparable interface :Compares values and returns an int which tells if the values compare less than, equal, or greater than.
If your class objects have a natural order, implement theComparable<T>
interface and define this method. All Java classes that have a natural ordering implementComparable<T>
- Example:String
, wrapper classes,BigInteger
compare(a, b)
:
Comparator interface :Compares values of two objects. This is implemented as part of theComparator<T>
interface, and the typical use is to define one or more small utility classes that implement this, to pass to methods such assort()
or for use by sorting data structures such asTreeMap
andTreeSet
. You might want to create a Comparator object for the following:- Multiple comparisons. To provide several different ways to sort something. For example, you might want to sort a Person class by name, ID, age, height, ... You would define a Comparator for each of these to pass to the
sort()
method. - System classTo provide comparison methods for classes that you have no control over. For example, you could define a Comparator for Strings that compared them by length.
- Strategy patternTo implement a Strategy pattern, which is a situation where you want to represent an algorithm as an object that you can pass as a parameter, save in a data structure, etc.
- Multiple comparisons. To provide several different ways to sort something. For example, you might want to sort a Person class by name, ID, age, height, ... You would define a Comparator for each of these to pass to the
a.compareTo(b)
:
Comparable 接口:比较值并返回一个 int 值,该 int 值表明这些值比较小于、等于还是大于。
如果您的类对象具有自然顺序,请实现Comparable<T>
接口并定义此方法。所有具有自然排序实现的 Java 类Comparable<T>
- 示例:String
、包装类、BigInteger
compare(a, b)
:
比较器接口:比较两个对象的值。这被实现为的一部分Comparator<T>
界面,并且典型的使用是定义一个或一个以上小工具类实现此,传递给方法,例如sort()
或通过排序数据结构,例如使用TreeMap
和TreeSet
。您可能希望为以下内容创建一个 Comparator 对象:- 多重比较。提供几种不同的排序方式。例如,您可能希望按姓名、ID、年龄、身高等对 Person 类进行排序……您可以为每个类定义一个 Comparator 以传递给该
sort()
方法。 - 系统类为您无法控制的类提供比较方法。例如,您可以为按长度比较字符串的字符串定义一个比较器。
- 策略模式要实现策略模式,这是一种您希望将算法表示为对象的情况,您可以将其作为参数传递,保存在数据结构中等。
- 多重比较。提供几种不同的排序方式。例如,您可能希望按姓名、ID、年龄、身高等对 Person 类进行排序……您可以为每个类定义一个 Comparator 以传递给该
If your class objects have one natural sorting order, you may not need compare().
如果您的类对象具有一种自然排序顺序,则您可能不需要 compare()。
Summary from http://www.digizol.com/2008/07/java-sorting-comparator-vs-comparable.html
摘要来自http://www.digizol.com/2008/07/java-sorting-comparator-vs-comparable.html
Comparable
A comparable object is capable of comparing itself with another object.
可比较
可比较对象能够将自身与另一个对象进行比较。
Comparator
A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class's instances.
比较
器 比较器对象能够比较两个不同的对象。该类不是比较它的实例,而是比较其他一些类的实例。
Use case contexts:
用例上下文:
Comparable interface
可比接口
The equals method and ==
and !=
operatorstest for equality/inequality, but do not provide a way to test for relative values.
Some classes (eg, String and other classes with a natural ordering) implement the Comparable<T>
interface, which defines a compareTo()
method.
You will want to implement Comparable<T>
in your class if you want to use it with Collections.sort()
or Arrays.sort()
methods.
equals 方法和==
和!=
运算符测试相等/不相等,但不提供测试相对值的方法。
一些类(例如,String 和其他具有自然顺序的类)实现了Comparable<T>
接口,该接口定义了一个compareTo()
方法。如果您想将它与或方法一起使用,
您将需要Comparable<T>
在您的类中实现。Collections.sort()
Arrays.sort()
Defining a Comparator object
定义 Comparator 对象
You can create Comparators to sort any arbitrary way for any class.
For example, the String
class defines the CASE_INSENSITIVE_ORDER
comparator.
您可以创建 Comparator 以任意方式对任何类进行排序。
例如,String
该类定义了CASE_INSENSITIVE_ORDER
比较器。
The difference between the two approaches can be linked to the notion of:
Ordered Collection:
两种方法之间的区别可以与以下概念联系起来:
Ordered Collection:
When a Collection is ordered, it means you can iterate in the collection in a specific (not-random) order (a Hashtable
is not ordered).
当 Collection 被排序时,这意味着您可以按特定(非随机)顺序(aHashtable
未排序)在集合中迭代。
A Collection with a natural orderis not just ordered, but sorted. Defining a natural order can be difficult!(as in natural String order).
具有自然顺序的Collection不仅是有序的,而且是有序的。定义自然顺序可能很困难!(如自然字符串顺序)。
Another difference, pointed out by HaveAGuessin the comments:
HaveAGuess在评论中指出的另一个区别:
Comparable
is in the implementation and not visible from the interface, so when you sort you don't really know what is going to happen.Comparator
gives you reassurance that the ordering will be well defined.
Comparable
是在实现中,从界面上看不到,所以当你排序时,你真的不知道会发生什么。Comparator
让您放心,排序将得到很好的定义。
回答by Yuval Adam
compareTo()
is from the Comparable
interface.
compareTo()
来自Comparable
界面。
compare()
is from the Comparator
interface.
compare()
来自Comparator
界面。
Both methods do the same thing, but each interface is used in a slightly different context.
两种方法都做同样的事情,但每个接口在稍微不同的上下文中使用。
The Comparableinterface is used to impose a natural ordering on the objects of the implementing class. The compareTo()
method is called the natural comparison method. The Comparatorinterface is used to impose a total ordering on the objects of the implementing class. For more information, see the links for exactly when to use each interface.
在可比接口用于强加于实现类的对象自然排序。该compareTo()
方法称为自然比较法。该比较器接口用于强加于实现类的对象进行整体排序。有关详细信息,请参阅有关确切何时使用每个界面的链接。
回答by Abgan
compareTo()
is called on one object, to compare it to another object.
compare()
is called on some object to compare two other objects.
compareTo()
在一个对象上调用,将其与另一个对象进行比较。
compare()
调用某个对象来比较两个其他对象。
The difference is where the logic that does actual comparison is defined.
不同之处在于定义进行实际比较的逻辑的位置。
回答by Ole
The relationship of the object having this method and its collaborators is different.
拥有此方法的对象与其合作者的关系是不同的。
compareTo()
is a method of the interface Comparable, so it is used to compare THIS instance to another one.
compareTo()
是接口Comparable 的一种方法,因此它用于将这个实例与另一个实例进行比较。
compare()
is a method of the interface Comparator, so it is used to compare two different instances of another class with each other.
compare()
是接口Comparator 的一个方法,因此它用于相互比较另一个类的两个不同实例。
If you will, implementing Comparable
means that instances of the class can be easily compared.
Implementing Comparator
means, that instances are suited to compare different objects (of other classes).
如果您愿意,实现Comparable
意味着可以轻松比较类的实例。
实现Comparator
意味着,实例适合比较不同的对象(其他类)。
回答by Markus Lausberg
When you want to sort a List which include the Object Foo, the Foo class has to implement the Comparable interface, because the sort methode of the List is using this methode.
当你想对一个包含对象 Foo 的 List 进行排序时,Foo 类必须实现 Comparable 接口,因为 List 的排序方法正在使用这个方法。
When you want to write a Util class which compares two other classes you can implement the Comparator class.
当您想编写一个比较两个其他类的 Util 类时,您可以实现 Comparator 类。
回答by Nicolai
The methods do not have to give the same answers. That depends on which objects/classes you call them.
这些方法不必给出相同的答案。这取决于您调用它们的对象/类。
If you are implementing your own classes which you know you want to compare at some stage, you may have them implement the Comparable interface and implement the compareTo() method accordingly.
如果您正在实现自己的类,并且知道要在某个阶段进行比较,则可以让它们实现 Comparable 接口并相应地实现 compareTo() 方法。
If you are using some classes from an API which do not implement the Comparable interface, but you still want to compare them. I.e. for sorting. You may create your own class which implements the Comparator interface and in its compare() method you implement the logic.
如果您使用的 API 中的某些类没有实现 Comparable 接口,但您仍然想比较它们。即用于排序。您可以创建自己的类来实现 Comparator 接口,并在它的 compare() 方法中实现逻辑。
回答by Michael Borgwardt
The main difference is in the use of the interfaces:
主要区别在于接口的使用:
Comparable (which has compareTo()) requires the objects to be compared (in order to use a TreeMap, or to sort a list) to implement that interface. But what if the class does not implement Comparable and you can't change it because it's part of a 3rd party library? Then you have to implement a Comparator, which is a bit less convenient to use.
Comparable(具有 compareTo())需要比较对象(为了使用 TreeMap 或对列表进行排序)来实现该接口。但是,如果该类没有实现 Comparable 并且您无法更改它,因为它是 3rd 方库的一部分怎么办?然后就得实现一个Comparator,使用起来有点不方便。
回答by jjnguy
Similarities:
Both are custom ways to compare two objects.
Both return an int
describing the relationship between two objects.
相似之处:
两者都是比较两个对象的自定义方法。
两者都返回一个int
描述两个对象之间关系的信息。
Differences:The method compare()
is a method that you are obligated to implement if you implement the Comparator
interface. It allows you to pass two objects into the method and it returns an int
describing their relationship.
区别:方法compare()
是实现Comparator
接口就必须实现的方法。它允许您将两个对象传递到该方法中,并返回一个int
描述它们之间关系的对象。
Comparator comp = new MyComparator();
int result = comp.compare(object1, object2);
The method compareTo()
is a method that you are obligated to implement if you implement the Comparable
interface. It allows an object to be compared to objects of similar type.
该方法compareTo()
是一种方法,如果您实现了该Comparable
接口,则您必须实现该方法。它允许将对象与类似类型的对象进行比较。
String s = "hi";
int result = s.compareTo("bye");
Summary:
Basically they are two different ways to compare things.
总结:
基本上,它们是比较事物的两种不同方式。
回答by dilip kumar
Comparableinterface contains a method called compareTo(obj)
which takes only one argument and it compares itself with another instance or objects of the same class.
Comparable接口包含一个被调用的方法compareTo(obj)
,该方法只接受一个参数,并将自身与同一类的另一个实例或对象进行比较。
Comparatorinterface contains a method called compare(obj1,obj2)
which takes two arguments and it compares the value of two objects from the same or different classes.
Comparator接口包含一个被调用的方法compare(obj1,obj2)
,它接受两个参数,它比较来自相同或不同类的两个对象的值。
回答by Bhabani Sankar Sahoo
Important Answar
String name;
int roll;
public int compare(Object obj1,Object obj2) { // For Comparator interface
return obj1.compareTo(obj1);
}
public int compareTo(Object obj1) { // For Comparable Interface
return obj1.compareTo(obj);
}
Here in return obj1.compareTo(obj1)
or return obj1.compareTo(obj)
statement
only take Object; primitive is not allowed.
For Example
这里 in return obj1.compareTo(obj1)
orreturn obj1.compareTo(obj)
语句只取 Object;原语是不允许的。例如
name.compareTo(obj1.getName()) // Correct Statement.
But
但
roll.compareTo(obj1.getRoll())
// Wrong Statement Compile Time Error Because roll
// is not an Object Type, it is primitive type.
name is String Object so it worked. If you want to sort roll number of student than use below code.
name 是 String Object 所以它有效。如果您想对学生的卷数进行排序,请使用以下代码。
public int compareTo(Object obj1) { // For Comparable Interface
Student s = (Student) obj1;
return rollno - s.getRollno();
}
or
或者
public int compare(Object obj1,Object obj2) { // For Comparator interface
Student s1 = (Student) obj1;
Student s2 = (Student) obj2;
return s1.getRollno() - s2.getRollno();
}