Determining the size relationship and arrangement order between two objects is called comparison. The class or method that can implement this comparison function is called a comparator. There are two kinds of comparisons in Java device.
Internal comparator (Comparable interface) and external comparator (Comparator interface)
1. The use of comparator sorting Comparator - can be regarded as a class (object ) External comparator (implements the Comparator interface).
To put it simply, the comparator is written outside the class, that’s right! Just define a new comparator class outside!
Define a new class. The class name is arbitrary, but this class must implement the Comparator interface and override the compare method. We call this an external comparator.
Case: Store student objects and traverse, create a TreeSet collection using the parameterized construction method.
Requirements: Sort by age from youngest to oldest. If the ages are the same, sort by name in alphabetical order.
Free learning video tutorial recommendation: java teaching video
Implementation steps: Use TreeSet collection to store custom objects, and the parameterized construction method uses a comparator to sort the elements Comparator sorting is to let the collection construction method receive the implementation class object of Comparator. When rewriting the compare(Student s1, Student s2) method, you must pay attention to the sorting rules that must be in accordance with the required primary and secondary conditions. Let’s write
1. Student category
2. Test category
2. Natural sorting The use of Comparable - class (object) internal comparator (implementing the Comparable interface):
To put it simply, the comparator is written inside the class.
The class (object) implements the Comparable interface, and then overrides the compareTo method (this method can be regarded as a comparator). This class has an internal comparator. Note that once you implement the comparator, it means that this class supports sorting
Implementation steps:
Use TreeSet collection to store custom objects, no-parameter construction method, using natural sorting of elements sorted.
Natural sorting means that the class to which the element belongs implements the Comparable interface and overrides the compareTo(Student s) method.
When rewriting the method, be sure to note that the sorting rules must be in accordance with the required main and Write secondary conditions.
1. Student category
2. Test category
Test result:
Recommended related articles and tutorials: Zero Basic Introduction to Java
The above is the detailed content of The difference between comparable and comparator in java. For more information, please follow other related articles on the PHP Chinese website!