首先创建一个学生类,其中包括了姓名,年龄,分数。构造函数进行赋值,重写toString方便打印。
class Student {
public String name;
public int age;
public int score;
public Student(String name,int age,int score){
this.name=name;
this.age=age;
this.score=score;
}
//重写可以鼠标右键点击gennerrate里面的override,也可直接输入overide等待idea进行提示
@Override
public String toString() {
return “Student{” +
“name='” + name + ‘’’ +
“, age=” + age +
“, score=” + score +
‘}’;
}
}
//然后对学生内进行初始化
public class Sort {
public static void main(String[] args) {
//建立学生类数组并进行赋值
Student[] student=new Student[3];
student[0]=new Student(“a”,18,99);
student[1]=new Student(“b”,28,45);
student[2]=new Student(“c”,25,92);
}
上面是对学生类的构建和初始化,接下来的代码紧跟着main中
1, 这个时候要对上面的结构体数组进行排序的话,可以通过冒泡排序通过每一个数组前缀去引用所要根据的什么排序:student[i].age。但是过于麻烦
接下来介绍两种对结构体数组进行排序的方式。
-
第一种就是联想到Arrays.sort()。在数组时可以直接对一个确定性数组进行排序。现在我们是要对student这个类进行排序,所以要对student这个类进行接口的连接,第一种用到的是compareable;
class Student implements Comparable<Student这里面为要排序的对象>{
//此时已经连接到Comparable接口,需要重写里面的CompareTo方法
public int compareTo(Student o) {
/if(this.age>o.age){
return 1;
}else if(this.age<o.age){
return -1;
}else {
return 0;
}/
//上面的代码可以简写为下面这个return 效果都是一样的
return this.age-o.age;
}
}
然后再调用
Arrays.sort(student);
System.out.println(Arrays.toString(student));
你就会惊奇的发现已经按照年龄排序了
但是细心的你就会发现,如果你想通过姓名,分数排序呢?所以这里的设定是很不灵活的,于是有了接下来的一种方法,比较器。 -
这里所用到的接口与前面的就有所不同了,为Comparator。这里请忘记我1上对student class的修改。Student现在就为一个很普通的学生类。下面首先要做的就是创建比较器,就是一个规定法则的类。
//年龄比较器
class AgeCompare implements Comparator<Student这里还是对谁排就写哪个对象>{
@Override
public int compare(Student o1, Student o2) {
return o1.age- o2.age;
}
}
//分数比较器
class ScoreCompare implements Comparator<Student这里还是对谁排就写哪个对象>{@Override
public int compare(Student o1, Student o2) {
return o1.score-o2.score;
}
}
//姓名比较器
class NameCompare implements Comparator<Student这里还是对谁排就写哪个对象>{
@Override
public int compare(Student o1, Student o2) {
return o1.name.compareTo(o2.name);
}
}
三个比较器已经构建完成,接下来就是对它的使用。还是用到的Arrays.sort()只是里面的参数多了一个比较器引用的对象。难道sort()里面还能放两个参数?因为sort这个方法,并不是只有这一个,方法重载相当于。
AgeCompare ageCompare=new AgeCompare();
Arrays.sort(student,ageCompare);
System.out.println(Arrays.toString(student));
System.out.println(“==“);
ScoreCompare scoreCompare=new ScoreCompare();
Arrays.sort(student,scoreCompare);
System.out.println(Arrays.toString(student));
System.out.println(”=”);
NameCompare nameCompare=new NameCompare();
Arrays.sort(student,nameCompare);
System.out.println(Arrays.toString(student));
上面就是代码实现,下面放结果
最后总结一下:对数组排序这里有三种方法,一是用排序方法(冒泡排序),引用自己想要根据什么来排序。二是在要排序的类里面重写CompareTo方法,接口用的是Comparable,该方法的缺点是不灵活。三用到的接口为Comparator,重写的compare方法,该方法就比较灵活,一次创建一直使用,想用什么调什么就好。