排序的算法,大家都不陌生,有冒泡排序、选择排序、插入排序,快速排序等等。如果现在有学生类,学校添加了很多学生,要你给学生按照学号大小排序,你会怎么排? 学生类 Student {int stuID; String stuName; int score; }
咱们java功能很强大,库里自带给数组排序的方法Arrays.sort(); 来看看它的相关用法:
头文件 import java.util.Arrays;
相关API:Arrays.sort(arys[])
Arrays.sort(arys[],int from,int to) //排序范围:from-->to-1
Arrays.sort(arys[],new MyComparator())
Arrays.sort(arys[],int from,int to,new MyComparator())
Arrays.sort()方法可对任何实现compareble接口的对象数组排序, 像Integer,String,这两种引用类型都实现了compareble接口,所以这两种类型的数组都可直接使用Arrays.sort()进行排序。这里我们看下api文档对compareble的描述:
想要了解底层实现加深理解可看我的上一篇博文模拟Arrays.sort实现自定义排序 : https://blog.csdn.net/zouzong123/article/details/81097109
public class Student implements Comparable {
private int stuId;
private String stuName;
private int score;
public Student(int stuId, String stuName, int score) {
this.stuId = stuId;
this.stuName = stuName;
this.score = score;
}
public int getStuId() {
return stuId;
}
public void setStuId(int stuId) {
this.stuId = stuId;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public int compareTo(Student o) {
return stuId-o.stuId;
}
@Override
public String toString() {
return "Student{" +
"stuId=" + stuId +
", stuName='" + stuName + '\'' +
", score=" + score +
'}';
}
}
咱们再建一个test类来测试下:
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
Student []students=new Student[]{
new Student(2,"张三",90),
new Student(3,"王老五",100),
new Student(1,"李四",87),
new Student(4,"小明",99)
};
Arrays.sort(students);
for (Student student:students
) {
System.out.println(student.toString());
}
}
}
效果如下: