Java 比较器和可比较之间有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22692777/
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 are the differences between comparator and comparable?
提问by Rantu
I need to understand the differences between comparable and comparator with proper examples. I have seen several books but the difference is not clear to me.
我需要通过适当的例子来理解可比较和比较之间的区别。我看过几本书,但我不清楚其中的区别。
回答by Thomas
Comparable
defines that instances of a class have a natural ordering, e.g. numbers which can be ordered small to big. In other cases this defines the default ordering, e.g. when using strings.
Comparable
定义类的实例具有自然排序,例如可以从小到大排序的数字。在其他情况下,这定义了默认排序,例如在使用字符串时。
A Comparator
on the other hand is an object that might define a non-standard ordering, i.e. you could provide a comparator to sort numbers from big to small for example.
Comparator
另一方面,A是一个可能定义非标准排序的对象,例如,您可以提供一个比较器来将数字从大到小排序。
回答by blackeyes123
Comparable interface: Class whose objects to be sorted must implement this interface.In this,we have to implement compareTo(Object) method.
Comparable接口:要排序的对象必须实现这个接口的类。在这个接口中,我们必须实现compareTo(Object)方法。
For example:
例如:
public class State implements Comparable{
@Override
public int compareTo(Object arg0) {
State state=(State) arg0;
return (this.stateId < state.stateId ) ? -1: (this.stateId > state.stateId ) ? 1:0 ;
}}
If any class implements comparable inteface then collection of that object can be sorted automatically using Collection.sort() or Arrays.sort().Object will be sort on the basis of compareTo method in that class.
如果任何类实现了可比较的接口,则可以使用 Collection.sort() 或 Arrays.sort() 自动对该对象的集合进行排序。对象将根据该类中的 compareTo 方法进行排序。
Objects which implement Comparable in java can be used as keys in a SortedMap like TreeMap or SortedSet like TreeSet without implementing any other interface.
在 Java 中实现 Comparable 的对象可以用作像 TreeMap 这样的 SortedMap 或像 TreeSet 这样的 SortedSet 中的键,而无需实现任何其他接口。
Comparator interface: Class whose objects to be sorted do not need to implement this interface.Some third class can implement this interface to sort.e.g.StateSortByIdComparator class can implement Comparator interface to sort collection of state object by id. For example:
Comparator接口:需要排序的对象的类不需要实现这个接口。第三个类可以实现这个接口到sort.egStateSortByIdComparator类可以实现Comparator接口,对状态对象集合进行id排序。例如:
public class StateSortByIdComparator implements Comparator<State>{
@Override
public int compare(State state1, State state2) {
return (state1.getStateId() < state2.getStateId() ) ? -1: (state1.getStateId() > state2.getStateId() ) ? 1:0 ;
}
}