Java中Comparator比较器的使用
说几点需要注意的,提醒自己即可:
以下是单独定义一个比较器的类,实现了Comparator中的compare方法。(要在Main方法外面定义类噢)
一定是compare而不是Compare哦
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);
}
}