This is the 12th day of my participation in Gwen Challenge

I. Introduce the Comparator

The Interface Comparator is an Interface to java.util. You can pass the Comparator to collections.sort or arrays.sort for precise control of sort order.

Using a Comparator

Yesterday’s example specified a collation rule for the Student array by implementing the Student class’s Comparable interface, specifying the primary and secondary keys for sorting. In practice, you may need to specify a variety of sorting rules, such as the sort by student number, or by name. At this point, you need to provide multiple comparators to fulfill the requirements.

The Comparator class is written to implement the Comparator interface. If there are several sorting rules, several Comparator classes need to be defined. Each class implements the Comparator interface respectively. The interface contains the compare method, which has two parameters: two objects with comparison, and the return value of the method is an integer.

With our comparators defined, we can use the Sort method of Arrays to sort objects. The sort method has the following format:

public static <T> void sort(T[] arr, Comparator<? super T> obj)

We can use it like this:

import java.util.Arrays;
import java.util.Comparator;
import example1.Student;	// Import the Student class from the previous example
public class ComparatorTest {
	public static void main(String[] args) {
		Student students[] = new Student[4];
		students[0] = new Student("A1502"."150202"."Zhang");
		students[1] = new Student("C1501"."150101"."Bill");
		students[2] = new Student("A1501"."150102"."Fifty");
		students[3] = new Student("B1502"."150101"."Horse six");
		System.out.println("-------- Original student information:");
		for (int i = 0; i < students.length; i++) {
			System.out.println(students[i]);
		}
		Arrays.sort(students, new IdComparator());
		System.out.println("-------- is sorted by student number as follows:");
		for (int i = 0; i < students.length; i++) {
			System.out.println(students[i]);
		}
		Arrays.sort(students, new NameComparator());
		System.out.println("-------- sorted by name as follows:);
		for (int i = 0; i < students.length; i++) { System.out.println(students[i]); }}}class IdComparator implements Comparator<Student> {
	public int compare(Student s1, Student s2) {
		int n = s1.getClassName().compareTo(s2.getClassName());
		if (n == 0) {
			return s1.getStudentId().compareTo(s2.getStudentId());
		} else {	returnn; }}}class NameComparator implements Comparator<Student> {
	public int compare(Student s1, Student s2) {
		returns1.getStudentName().compareTo(s2.getStudentName()); }}Copy the code