首先,数组中的元素即被排序的对象要实现comparable接口及其compareTo(Object o)方法
第二步,通过Arrays.sort(Object[] a) 对数据进行排序
class Student implements Comparable{
int age;
String name;
public Student(int age,String name){
this.age = age;
this.name = name;
}
public int compareTo(Object o){
Student s = (Student)o;
return age>s.age ? 1 : (age==s.age ? 0 : -1);
}
}
第二步,通过Arrays.sort(Object[] a) 对数据进行排序
Student[] students = Student[]{new Student(10,"zhangsan"),new Student(20,"lisi"),new Student(30,"wangwu")};
Arrays.sort(students);
本文介绍了一个使用Java实现的排序示例。示例中定义了一个学生类,并实现了Comparable接口及compareTo方法,用于比较学生的年龄大小。随后,利用Arrays.sort方法对包含多个学生的数组进行了排序。

被折叠的 条评论
为什么被折叠?



