如何在字段级别对Java中的对象数组进行排序以进行成绩比较?

时间:2012-07-11 01:37:51

标签: java string sorting compare

在Java中,

Class StudentProgress
{
        String Name;
        String Grade;
        /* CTOR goes here */
}

main class
{
     main method()
     {
         StudentProgress arrayofObjects[100000];
     }
}

如果等级为D-,C-,B-,A-,A,B,C,D,A +,B +,C +,D +。我需要对这些对象进行排序,如何才能有效地完成它 提前致谢

2 个答案:

答案 0 :(得分:6)

您最好的方法是让您的班级实施Comparable。这样的事情会起作用:

public class StudentProgress implements Comparable<StudentProgress> {

    String name;
    String grade;
    char baseGrade;    // Just the letter
    int gradeModifier; // -1 0 or +1 - done to make sorting easier

    public StudentProgress( String name, String grade ) {
        this.name = name;
        this.grade = grade;
        // Extract the grade parts for use when comparing
        baseGrade = grade.charAt( 0 );
        gradeModifier = grade.length() == 1 ? 0 : Integer.parseInt( grade.charAt( 1 ) + "1" );
    }

    public int compareTo( StudentProgress o ) {
        return baseGrade == o.baseGrade ? gradeModifier - o.gradeModifier : baseGrade - o.baseGrade;
    }
}

然后要排序,只需使用Arrays.sort()方法:

StudentProgress[] array = ...;
Arrays.sort(array);

如果您不希望您的班级实施此界面,您可以为排序调用提供独立的Comparator

答案 1 :(得分:3)

您正在寻找的课程是Comparable和Comparator。

本教程将指导您http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/

祝你好运!