View Single Post
Old 10-22-2008, 05:29 PM   PM User | #8
shyam
Senior Coder

 
shyam's Avatar
 
Join Date: Jul 2005
Posts: 1,563
Thanks: 2
Thanked 163 Times in 160 Posts
shyam will become famous soon enough
Quote:
Originally Posted by ctbalamurali View Post
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));
__________________
You never have to change anything you got up in the middle of the night to write. -- Saul Bellow
shyam is offline   Reply With Quote