题目:定义小学生类:属性:年领,身高;
定义一个方法,接收一个小学生类数组,用Comparable接口实现排序;
comparable:年龄大的排前面(年龄降序),年龄若相等,则比身高,高的排后面(身高升序);
代码:
import java.util.Arrays;
public class Test2 {
/*
* 3、定义小学生类:属性:年领,身高;
定义一个方法,接收一个小学生类数组,用Comparator和Comparable接口分别实现排序
comparable:年龄大的排前面(年龄升序),年龄若相等,则比身高,高的排后面(身高升序);
comparator:先对身高进行降序排列,如果身高相同,则按照年龄升序
*/
public static void main(String[] args) {
test1();
}
private static void test1() {
Pupil [] pupils = new Pupil[5];
pupils[0] = new Pupil("一", 16, 200);
pupils[1] = new Pupil("二", 16, 180);
pupils[2] = new Pupil("三", 14, 210);
pupils[3] = new Pupil("四", 18, 222);
pupils[4] = new Pupil("五", 19, 200);
//对数组进行排序
sort(pupils);
//输出排序后的学生数组
System.out.println(Arrays.toString(pupils));
}
private static void sort(Pupil [] pupils) {
Arrays.sort(pupils);
}
}
//定义小学生类实现Comparable接口,并且制定类型为Pupil,(也可以指定为Object型,但比较时需要向下转型)
class Pupil implements Comparable<Pupil>{
String name;
int age;
int height;
public Pupil() {
super();
// TODO Auto-generated constructor stub
}
public Pupil(String name, int age, int height) {
super();
this.name = name;
this.age = age;
this.height = height;
}
@Override
public String toString() {
return "Pupil [name=" + name + ", age=" + age + ", height=" + height + "]";
}
//这里重写了Comparable 接口中的方法;并且按年龄升序,按身高也是升序;
@Override
public int compareTo(Pupil o) {
if(this.age>o.age) {
return 1;
}else if(this.age<o.age) {
return -1;
}else if(this.age==o.age) {
return this.height-o.height;
}
return 0;
}
}