提供一个独立的
在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+。我需要对这些对象进行排序如何才能有效地进行排序提前感谢
最好的方法是让类实现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
您要查找的类是Comparable和Comparator。
本教程将指导您,http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/
祝你好运!