Recently, the function of doing an object sort needs to be sorted by different rules. Look at the arrays,collections, the Sort method,
Learn about the Comparator,comparable two interfaces, find the sort method that applies to yourself, and below put your own
Understand and collect what I think is the classic explanation as follows:
Comparable is a general-purpose interface that users can implement to perform their own specific comparisons, while comparator can be seen as an implementation of an algorithm that specifies the comparator when a container set collection needs to compare functions, which shows a design pattern Separates the algorithm from the data, just like the function object in the C + + STL.
The former should be more fixed and binding to a specific class, which is flexible and can be used for each class that needs to compare functions. It can be said that the former belongs to "static binding", while the latter can be "dynamic binding."
A class implements a Camparable interface that indicates that objects of this class can be compared to each other. If it is described in mathematical language, there is a whole sequence in the set of objects of this class. This way, the collection of class objects can be sorted by using the Sort method.
And the comparator has two functions:
1. If the class designers do not take into account the compare of the problem and do not implement the comparable interface, you can use comparator to implement the comparison algorithm to sort
2. Prepare for the use of different sorting criteria, such as ascending, descending, or other sequence