How to sort an array of objects in Java in field level for grade comparison?

家住魔仙堡 提交于 2019-12-12 15:18:48

问题


In Java,

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

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

If the Grades are like D-,C-,B-,A-,A,B,C,D,A+,B+,C+,D+. I need to sort these objects how can I do it efficiently Thanks in advance


回答1:


Your best approach is to make your class implement Comparable. Something like this will work:

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

Then to sort, you simply use the Arrays.sort() method:

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

If you don't want your class to implement this interface, you can provide a stand-alone Comparator to the sort call




回答2:


The classes you are looking for is, Comparable and Comparator.

This tutorial will guide you, http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/

Good luck!



来源:https://stackoverflow.com/questions/11424369/how-to-sort-an-array-of-objects-in-java-in-field-level-for-grade-comparison

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!