首页 新闻 会员 周边 捐助

ostudent类按照年龄排序,通过实现comparable接口怎么重写其父类的compareTo方法

0
悬赏园豆:5 [待解决问题]

package cj.comparableImplemtnt;

import java.util.Arrays;

public class Student implements Comparable{
public static void main(String[] args) {
Student stu1=new Student("lilei", true, 12, "北京大学");
Student stu2=new Student("Tom", true, 19, "南京大学");
Student stu3=new Student("WangJuan", false, 13, "复旦大学");
Student stu4=new Student("Hellen", false, 17, "四川大学");
Student[] stu={stu1,stu2,stu3,stu4,};
Arrays.sort(stu);
for (int i = 0; i < stu.length; i++) {
System.out.println(stu[i].toString());
}
}


private String name;
private boolean sex;
private int age;
private String school;
public Student() {

}

public Student(String name, boolean sex, int age, String school) {
this.name = name;
this.sex = sex;
this.age = age;
this.school = school;
}
public String getName() {
return name;
}
public boolean isSex() {
return sex;
}
public int getAge() {
return age;
}
public String getSchool() {
return school;
}

public String toString() {
return " " + name + " " + (sex?"m":"f") + " " + age + " " + school;
}
//以年龄字段排序
public int compareTo(Object obj) {
Student stu=(Student)obj;
if(this.age-stu.age<0){
return 1;
}else if(this.age-stu.age>0){
return -1;
}else{
return 0;
}


}


}

cj_java_web的主页 cj_java_web | 初学一级 | 园豆:17
提问于:2016-06-15 21:45
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册