现在有person类,
person类中有两个属性 
String name; 
int score;怎样将person类的对象按score排序? 

解决方案 »

  1.   


        public class SaComparator implements Comparator { @Override
    public int compare(Object o1, Object o2) {
    Person type1 = (Person)o1;
    Persont ype2 = (Person)o2;
    if(type1.getScore()>type2.getScore()){
    return 1;//升序
    }else{
    return -1;
    }

    }
    }
    List<Person> list = new ArrayList<Person>()
    list.add(new Person("a",60));
    list.add(new Person("b",80));
    SaComparator sc = new SaComparator()
    list.sort(list,sc);这样就是排序好的
    如果到倒序的话type1.getScore()>type2.getScore()的时候返回-1就可以了
      

  2.   


    import java.util.Set;
    import java.util.TreeSet;public class C {
    public static void main(String[] args) {
    Set<Student> set = new TreeSet<Student>();
    Student1 s1, s2, s3;
    // 实例化对象
    s1 = new Student();
    s1.name = "zhangsan";
    s1.score = 70;
    s2 = new Student();
    s2.name = "ls";
    s2.score = 60;
    s3 = new Student();
    s3.name = "ww";
    s3.score = 80;
    set.add(s1);
    set.add(s2);
    set.add(s3);
    for (Student stu : set) {
    System.out.println(stu.score);
    }
    }}class Student1 implements java.lang.Comparable {
    String name; int score; public int compareTo(Object o) {
    Student stu = (Student) o;
    if (this.score > stu.score) {
    return 1;
    }
    if (this.score == stu.score) {
    return 0;
    }
    return -1;
    }
    }好像昨天也看到一个以name排序的...
      

  3.   

    Student1改成Student
      

  4.   

    如果是在页面上显示的话,可以用JQUERY的tableSorter实现很简单。
    如果要用JAVA来实现的话,那就写个循环
      

  5.   

    上次我也给你回答过按name排序的,但上次回答score时给弄错了,现在在这将功赎罪,希望不介意。import java.util.*;
    public class Student implements Comparable<Student>
    {
    public Student(String name ,int score)
    {
    this.name = name;
    this.score = score;
    }
    public int compareTo(Student other)
    {
    if(score<other.score)
    return -1;
    if(score>other.score)
    return 1;
    else
    return 0;
    }
    public String toString()
    {
    return "score : "+score+",name : "+name;
    }
    public static void main(String[] args)
    {
    Student[] student = new Student[3];
    student[0] = new Student("ang san",3);
    student[1] = new Student("bruse si",1);
    student[2] = new Student("chang hu",9);

    Arrays.sort(student);
    for(Student s:student)
    System.out.println(s);
    }
    private String name;
    private int score;
    }