在Arrays类中定义了一下的一个方法,可以直接为一个对象数组进行排序:
public static void sort(Object[] a)
1.问题引出
定义一个学生类 包括属性和方法 按成绩排序 如果成绩相等,则按照年龄进行排序。
package org.lxh.comparesdemo;
import java.util.Arrays;
class Student {
private int stuno;
private String name;
private int age;
private float score;
public Student(int stuno, String name, int age, float score) {
this.stuno = stuno;
this.name = name;
this.age = age;
this.score = score;
}
public String toString() { // 覆写toString()
return "学生编号:" + this.stuno + ";姓名:" + this.name + ";年龄:" + this.age
+ ";成绩:" + this.score;
}
}
public class CompareDemo01 {
public static void main(String[] args) {
Student stu[] = { new Student(1, "张三", 21, 99.1f),
new Student(2, "李四", 20, 99.1f),
new Student(3, "王五", 21, 89.1f),
new Student(4, "赵六", 21, 80.1f),
new Student(5, "孙七", 19, 80.1f) };
System.out.println("============== 数组声明之前 ===============");
print(stu);
System.out.println("============== 数组排序之后 ===============");
Arrays.sort(stu);// 排序
print(stu);
}
public static void print(Student stu[]) {
for (int i = 0; i < stu.length; i++) {
System.out.println(stu[i]);
}
}
}
以上程序会出现类的转换异常。在sort()方法中强调,如果要想实现对象数组的排序,则所有的元素都必须实现Comparable接口
2.Comparable接口
Comparable接口实际上属于比较器的操作接口,此接口定义如下:
public interface Comparable<T>{ //接口上使用了泛型
int compareTo(T o){ //定义compareTo()方法,此方法完成排序的
//比较代码
}
}
关于CompareTo()方法的返回值三种
小于:-1 等于:0 大于:1
package org.lxh.comparesdemo;
/*
import java.util.Arrays;
class Student implements Comparable<Student> { // 实现比较器,并指定泛型
private int stuno;
private String name;
private int age;
private float score;
public Student(int stuno, String name, int age, float score) {
this.stuno = stuno;
this.name = name;
this.age = age;
this.score = score;
}
public int compareTo(Student stu) {
if (this.score > stu.score) {
return -1;
} else if (this.score < stu.score) {
return 1;
} else {
if (this.age > stu.age) {
return 1;
} else if (this.age < stu.age) {
return -1;
} else {
return 0;
}
}
}
public String toString() { // 覆写toString()
return "学生编号:" + this.stuno + ";姓名:" + this.name + ";年龄:" + this.age
+ ";成绩:" + this.score;
}
}
public class CompareableDemo01 {
public static void main(String[] args) {
Student stu[] = { new Student(1, "张三", 21, 99.1f),
new Student(2, "李四", 20, 99.1f),
new Student(3, "王五", 21, 89.1f),
new Student(4, "赵六", 21, 80.1f),
new Student(5, "孙七", 19, 80.1f) };
System.out.println("============== 数组声明之前 ===============");
print(stu);
System.out.println("============== 数组排序之后 ===============");
Arrays.sort(stu);// 排序
print(stu);
}
public static void print(Student stu[]) {
for (int i = 0; i < stu.length; i++) {
System.out.println(stu[i]);
}
}
}
*/