java中实现Comparable接口实现自定义排序的示例
程序员文章站
2024-02-28 10:22:28
实例如下所示:
class student implements comparable{
string name;
int gpa;
@over...
实例如下所示:
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接口实现自定义排序的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。