//你实现这个接口,必须实现接口的抽象方法 public class Student implements Comparable { String name; int age; public Student( String name,int age) { this.age = age; this.name = name; } /** * @name 比较对象的大小 安照年龄比较,年龄相同安装姓名比较 * @param obj 要比较的对象 * @return int 0=相等 1 大于,-1 小于 9 表示不是同类型 */ @Override public int compareTo(Object obj) { int i = 0; //地址比较 if(this == obj) { i = 0; } //类型检查 非我族类其心必异 //提升 stu 的作用域 Student stu = null; if(obj instanceof Student) { //向下转型为 Student 类 stu = (Student)obj; }else { //非我族类 i = 9; } //比较年龄 if(this.age == stu.age) { //比较 姓名 return this.name.compareTo(stu.name); } if(this.age > stu.age) { i = 1; } if(this.age < stu.age) { i = -1; } System.out.println("this.age:"+this.age+"=============="+stu.age); return i; } }
开始比较:
public class TestStudent { public static void main(String[] args) { Student[] stu = new Student[3]; stu[0] = new Student("张三", 17); stu[1] = new Student("李四", 18); stu[2] = new Student("王二", 19); int res = stu[0].compareTo(stu[2]); System.out.println(res); } }
比较结果:
this.age:17==============19
-1
欢迎拍砖。。。。。。。。。。。。。。。。。。。。。。。。。。