下面小编就为大家带来一篇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中文网其他相关文章!