Quote:
Originally Posted by ctbalamurali
while craeting the student object in rn=untime sorting order need to be passed. once it order is passed then it will get sorted what ever the way it wants. This is called dynamic variable sir
|
did you try this?
Code:
Student[] students = new Student[3];
students[0] = new Student(new Long (52645),"Smith","Bob",true);
students[1] = new Student(new Long (98765),"Jones","Will",false); // looks like Jones does not like being sorted in ascending :O
students[2] = new Student(new Long (1354),"Johnson","Matt",true);
/* Sort array */
Arrays.sort(students);
sorting as an operation should not have any dependency on the operands...Fou-lu has given the solution using the Comparable interface...Here's how you can do it using the Comparator interface (casting aside doubts whether rajeshnaidu has completed his homework :/ )
Code:
class StudentComparator implements Comparator<Student> {
boolean ascending = true;
public StudentComparator(boolean ascending) {
this.ascending = ascending;
}
public int compare(Student arg0, Student arg1) {
return ascending ? arg0.student_id.compareTo(arg1.student_id) : arg1.student_id.compareTo(arg0.student_id);
}
}
...
// ascending
Arrays.sort(students, new StudentComparator(true));
//descending
Arrays.sort(students, new StudentComparator(false));