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

list排序
要对总成绩SUM排序可是好像还是不对,还有要要按照输入id或sum排序,这怎么实现

Java code
import java.util.Comparator;

public class CoComparator implements Comparator {

    @Override
    public int compare(Object a0, Object a1) {
    Student s1 =(Student) a0;
    Student s2 = (Student) a1;
         if (s1.getSum()<s2.getSum()){
             return 1;
         }else{
             return 0;
         }
    }
    

}

Java code
]import java.util.ArrayList;
import java.util.Iterator;

import java.util.Collections;

public class Test {
    public static void main(String[] args) {
        Student s1 = new Student("haha",1,12,13);
        Student s2 = new Student("xixi",2,11,15);
        Student s3 = new Student("wowo",3,10,14);
        
        ArrayList a = new ArrayList();
        a.add(s1);
        a.add(s2);
        a.add(s3);
        
        CoComparator co = new CoComparator();
        Collections.sort(a,co);
        
        
        Iterator it = a.iterator();
        Student ss;
        
        while(it.hasNext()){
        ss=(Student)it.next();
        System.out.println(ss.name+"   "+ss.id+"    "+ss.getSum());
        }
        
        
    }[/code
[code=Java]public class Student {
    String name;
    int id;
    double math;
    double english;
    double sum;
    
    public Student(String name, int id, double math, double english) {
        this.name = name;
        this.id = id;
        this.math = math;
        this.english = english;
    }

    public double getSum() {
        return sum=math+english;
    }

}


------解决方案--------------------
comparetor,加上泛型

比较是:
大于返回1,等于返回0,小于返回-1

Integer的compareTo方法的源码
Java code

    /**
     * Compares two <code>Integer</code> objects numerically.
     *
     * @param   anotherInteger   the <code>Integer</code> to be compared.
     * @return    the value <code>0</code> if this <code>Integer</code> is
     *         equal to the argument <code>Integer</code>; a value less than
     *         <code>0</code> if this <code>Integer</code> is numerically less
     *         than the argument <code>Integer</code>; and a value greater 
     *         than <code>0</code> if this <code>Integer</code> is numerically
     *          greater than the argument <code>Integer</code> (signed
     *          comparison).
     * @since   1.2
     */
    public int compareTo(Integer anotherInteger) {
    int thisVal = this.value;
    int anotherVal = anotherInteger.value;
    return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
    }