日期:2014-05-20  浏览次数:20785 次

对象排序
ArrayList<Student> list=new ArrayList<Student>();
Student a=new Student("胖胖",20,90.5);
Student b=new Student("刘静",20,92.5);
Student c=new Student("苏凯",20,80.5);
Student d=new Student("许三多",20,90.5);
Student e=new Student("成才",20,90.5);
list.add(a);
list.add(b);
list.add(c);
list.add(d);
list.add(e);


按成绩排序,从高到低

------解决方案--------------------
Java code


import java.util.ArrayList;
import java.util.Collections;


public class StudentRanging {
    public static void main(String[] args) {
        ArrayList<Student> list=new ArrayList<Student>();
        Student a=new Student("胖胖",20,90.5);
        Student b=new Student("刘静",20,92.5);
        Student c=new Student("苏凯",20,80.5);
        Student d=new Student("许三多",20,90.5);
        Student e=new Student("成才",20,90.5);
        list.add(a);
        list.add(a);
        list.add(b);
        list.add(c);
        list.add(d);
        list.add(e);
        Collections.sort(list);
        for(Student s:list){
            System.out.println("info:"+s);
        }
    }

}

class Student implements Comparable{
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }

    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;
    }

    private String name;
    private int age;

    Student(String name, int age, double score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    private double score;


    @Override
    /**
     * 实现按照成绩降序排序
     */
    public int compareTo(Object o) {
        Student s=(Student)o;
        int result=0;
        if(this.score>s.getScore())
           result=-1;
        if(this.score<s.getScore())
           result=1;
        return result; 
    }
}