java中实现Comparable接口实现自定义排序
 1 class Student implements Comparable{
 2     String name;
 3     int gpa;
 4     @Override
 5     public int compareTo(Object arg0) {
 6         // TODO Auto-generated method stub
 7         Student s = (Student)arg0;
 8         
 9         if(gpa == s.gpa) return name.compareTo(s.name);
10         else if(gpa < s.gpa) return -1;
11         else if(gpa > s.gpa) return 1;
12         else return 0;
13         
14     }
15     
16     
17 }
18 
19 class Test {
20     public static void main(String[] args){
21         Scanner in = new Scanner(System.in);
22         
23         int n = in.nextInt();
24         
25         Student[] s = new Student[n];
26         
27         for(int i = 0;i < n;i ++){
28             s[i] = new Student();
29             s[i].name = in.next();
30             s[i].gpa = in.nextInt();
31         }
32         
33         Arrays.sort(s);
34         
35         for (Student ss : s)  
36         {  
37             System.out.println(ss.name);  
38             System.out.println(ss.gpa);  
39         }  
40     }
41 }

 

posted on 2017-09-25 16:37  Stephenatalie  阅读(1357)  评论(0编辑  收藏  举报