本帖最后由 Без_тебя 于 2014-6-13 01:31 编辑
有3个类,Student类,SortUtil排序工具类,demo类
大概思路,在Student上继承了Comparable接口,实现了compareTo的方法,用成绩来比较学生的大小问题,然后通过了SortUtil进行冒泡法排序,在demo2中输出~~~
class Student implements Comparable<Student> {
private String name;
private int age;
private double score;
public Student(){
}
public Student(String name, int age, double score){
this.name=name;
this.age=age;
this.score=score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public int compareTo(Student stu) {
return (int) (this.score-stu.getScore());
}
@Override
public String toString(){
return "姓名:"+this.name+" 年龄:"+this.age+" 成绩:"+this.score;
}
}
/* * 这边的SortUtil可以把任何类型的数组用冒泡排序法进行排序,有兴趣的同学可以看看,是泛型的灵活使用
*/
class SortUtil {
public static <T extends Comparable<T>> T[] sort(T[] arr){
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr.length-1;j++){
if(arr[j].compareTo(arr[j+1])>0){
T temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
}
import java.util.ArrayList;
import java.util.List;
public class demo2 {
public static void main(String[] args) {
Student stu1 = new Student("aaa",11,88.0);
Student stu2 = new Student("bbb",13,90.0);
Student stu3 = new Student("aaa",11,88.0);
Student stu4 = new Student("bbb",13,91.0);
Student stu5 = new Student("aaa",13,82.0);
Student stu6 = new Student("bbb",12,94.0);
Student stu7 = new Student("aaa",15,81.0);
Student stu8 = new Student("bbb",16,91.0);
List<Student> list = new ArrayList<Student>();
Student[] stus = new Student[]{stu1,stu2,stu3,stu4,stu5,stu6,stu7,stu8};
Student[] s2 = SortUtil.sort(stus);
for(Student s : s2){
System.out.println(s);
}
}
}
|
|