如何在字段级别中对Java中的对象数组进行排序以进行成绩比较? [英] How to sort an array of objects in Java in field level for grade comparison?

查看:210
本文介绍了如何在字段级别中对Java中的对象数组进行排序以进行成绩比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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 +。我需要对这些对象进行排序。
提前感谢

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

推荐答案

您的课程实施 可比较 。这样的东西将工作:

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

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

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

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

如果你不想让你的类实现这个接口,你可以提供一个独立的 Comparator 到排序调用

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

这篇关于如何在字段级别中对Java中的对象数组进行排序以进行成绩比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆