问题
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