实例如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
class Student implements Comparable{ String name; int gpa; @Override public int compareTo(Object arg0) { // TODO Auto-generated method stub Student s = (Student)arg0; if(gpa == s.gpa) return name.compareTo(s.name); else if(gpa < s.gpa ) return -1; else if(gpa > s.gpa) return 1; else return 0; } } class Test { public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); Student[] s = new Student[n]; for(int i = 0;i < n;i ++){ s[i] = new Student(); s[i].name = in.next(); s[i].gpa = in.nextInt(); } Arrays.sort(s); for (Student ss : s) { System.out.println(ss.name); System.out.println(ss.gpa); } } } |
以上这篇java中实现Comparable接口实现自定义排序的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/anqiang1995/p/7592595.html