本篇文章小编给大家分享一下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{
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);
}
}