原创作品,允许转载,转载时请务必以超链接形式标明文章
原始出处 、作者信息和本声明。否则将追究法律责任。
http://haiyuanxi.blog.51cto.com/4230602/931163
class Student
implements Comparable<Student> {
// 指定类型为Student
private String name;
private int age;
private float score;
public Student(String name, int age, float score) {
super();
this.name = name;
this.age = age;
this.score = score;
}
@Override
public int compareTo(Student student) {
// 覆写compareTo()方法,实现排序规则的应用
// 先按成绩排
if ( this.score > student.score) {
// 成绩大
return -1; //改变1和-1的值就可以改变排序的顺序
} else if ( this.score < student.score) {
// 成绩小
return 1;
} else {
// 成绩相等再按年龄排序
if ( this.age > student.age) {
// 年龄大
return 1;
} else if ( this.age < student.age) {
// 年龄小
return -1;
} else {
return 0;
}
}
}
@Override
public String toString() {
// TODO Auto-generated method stub
return name + "\t\t" + this.age + "\t\t" + this.score;
}
}
public class ComparableDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu[] = { new Student( "yanjun1", 20, 38),
new Student( "yanjun2", 23, 44), new Student( "yanjun3", 24, 44),
new Student( "yanjun4", 20, 45) };
java.util.Arrays.sort(stu); //直接通过java.util.Arrays.sort(stu);排序
//按成绩排序
System.out.println( "按成绩排序");
for ( int i = 0; i < stu.length; i++) {
System.out.println(stu[i]);
}
}
}
private String name;
private int age;
private float score;
public Student(String name, int age, float score) {
super();
this.name = name;
this.age = age;
this.score = score;
}
@Override
public int compareTo(Student student) {
// 覆写compareTo()方法,实现排序规则的应用
// 先按成绩排
if ( this.score > student.score) {
// 成绩大
return -1; //改变1和-1的值就可以改变排序的顺序
} else if ( this.score < student.score) {
// 成绩小
return 1;
} else {
// 成绩相等再按年龄排序
if ( this.age > student.age) {
// 年龄大
return 1;
} else if ( this.age < student.age) {
// 年龄小
return -1;
} else {
return 0;
}
}
}
@Override
public String toString() {
// TODO Auto-generated method stub
return name + "\t\t" + this.age + "\t\t" + this.score;
}
}
public class ComparableDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu[] = { new Student( "yanjun1", 20, 38),
new Student( "yanjun2", 23, 44), new Student( "yanjun3", 24, 44),
new Student( "yanjun4", 20, 45) };
java.util.Arrays.sort(stu); //直接通过java.util.Arrays.sort(stu);排序
//按成绩排序
System.out.println( "按成绩排序");
for ( int i = 0; i < stu.length; i++) {
System.out.println(stu[i]);
}
}
}