下面小編就為大家帶來一篇java中實作Comparable介面實作自訂排序的範例。小編覺得蠻不錯的,現在就分享給大家,也給大家做個參考。一起跟著小編過來看看吧
實例如下圖:
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介面以及自訂排序的實作範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!