Dynamic variable can be passed to determine the the sorting order
Please find the updated sample code. Thanks
[PHP]Sample code:
Camparable Object:
PHP Code:
package Sorting;
public class Student implements Comparable {
public Long student_id;
public String last_name;
public String first_name;
public boolean isAsc;
public Student(Long student_id, String last_name, String first_name, boolean isAsc) {
this.student_id = student_id;
this.last_name = last_name;
this.first_name = first_name;
this.isAsc = isAsc;
}
/* Overload compareTo method */
public int compareTo(Object obj) {
Student tmp = (Student) obj;
if (tmp.isAsc == true) {
if (this.student_id.compareTo(tmp.student_id) < 0) {
/* instance lt received */
return -1;
} else if (this.student_id.compareTo(tmp.student_id) > 0) {
/* instance gt received */
return 1;
}
} else // Desending
{
if (this.student_id.compareTo(tmp.student_id) > 0) {
/* instance gt received */
return -1;
} else if (this.student_id.compareTo(tmp.student_id) < 0) {
/* instance lt received */
return 1;
}
}
return 0;
}
}
It's main method:
PHP Code:
package Sorting;
import java.util.Arrays;
public class SortMain {
public static void main(String[] args)
{
/* Create an array of Student object */
Student[] students = new Student[3];
students[0] = new Student(new Long (52645),"Smith","Bob",true);
students[1] = new Student(new Long (98765),"Jones","Will",true);
students[2] = new Student(new Long (1354),"Johnson","Matt",true);
/* Sort array */
Arrays.sort(students);
/* Print out sorted values */
for(int i = 0; i < students.length; i++)
{
System.out.println(students[i].student_id +
students[i].last_name + students[i].first_name);
}
// Desendig
/* Create an array of Student object */
students[0] = new Student(new Long (52645),"Smith","Bob",false);
students[1] = new Student(new Long (98765),"Jones","Will",false);
students[2] = new Student(new Long (1354),"Johnson","Matt",false);
/* Sort array */
Arrays.sort(students);
/* Print out sorted values */
for(int i = 0; i < students.length; i++)
{
System.out.println(students[i].student_id +
students[i].last_name + students[i].first_name);
}
}
}