当前位置:网站首页>What is the difference between comparator and comparable?

What is the difference between comparator and comparable?

2022-06-23 03:33:00 , country

The same thing
Both are used to compare two objects The order The interface of
You can use Collections.sort() Method to sort the collection of objects
Difference
Comparable be located java.lang It's a bag , and Comparator At java.util It's a bag
Comparable It's a sort of method implementation defined within a collection ,Comparator It's a sort implemented outside the collection
summary
Use Comparable Interface to compare objects , You can make this type ( Set to A) Realization Comparable Interface , and
have access to Collections.sort() Method A Type of List Sort , And then you can go through a1.comparaTo(a2) Let's compare two
object ;
When using Comparator Interface to compare objects , Just create an implementation Comparator Comparator of interface ( set up
by AComparator), And pass it on Collections.sort() The method can be used to A Type of List Sort , You can also adjust
Use a comparator AComparator.compare(a1, a2) To compare two objects .
It can be said that one is to complete the comparison by oneself , One is the difference between the implementation of external programs .
use Comparator It's the strategy model (strategy design pattern), It's not changing the object itself , And with a strategy object
strategy object) To change its behavior .
such as : You want to sort integers in absolute size ,Integer It doesn't meet the requirements , You don't need to modify Integer class ( actual
You can't do that ) To change its ordering behavior , At this time, just ( There is only a ) Using an implementation Comparator Interface
Object to control its sorting .
Two ways , Each has its own characteristics : Use Comparable When comparing ways , We write the rules of comparison into the type of comparison , Its
Characterized by high cohesion . But if one day this rule needs to be changed , So we have to modify the source code of this type . If you use
Comparator Way comparison , So we don't need to modify the comparison class , It is easy to maintain , But you need to customize a comparator ,
Subsequent changes to the comparison rules , Just change the code in the comparator .
原网站

版权声明
本文为[, country]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202211734217236.html