The use of Java in the Comparator comparator

Say a few things to pay attention, you can remind yourself:
The following is the definition of a single comparator class that implements Comparator compare methods of. (In the Main method to define a class outside oh)
must instead compare Compare oh

package xixixi;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        Student[] arr = new Student[n];
        for(int i=0;i<n;i++)
        {
            String name = in.next();
            int num = in.nextInt();
            arr[i] = new Student(name, num);
        }
    }   
}

class Student{
    String name;
    int num;
    Student(String s,int n){
        name = s;
        num = n;
    }
    
    public String toString() {
        return name+"-"+num;
    }
}

 class NameComparator implements Comparator<Student>{
    public int compare(Student o1,Student o2)
    {
        if(o1.name.compareTo(o2.name)>0)
            return 1;
        else if(o1.name.compareTo(o2.name)<0)
            return -1;
        else 
            return o1.name.compareTo(o2.name);
    }
}

Guess you like

Origin www.cnblogs.com/juzijuziju/p/12129060.html