View Single Post
Old 10-20-2008, 05:47 PM   PM User | #4
ctbalamurali
New to the CF scene

 
Join Date: Oct 2008
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
ctbalamurali is an unknown quantity at this point
Solution: Dynamic variable can be passed to determine the the sorting order

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_idString last_nameString first_nameboolean 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 = (Studentobj;

        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 0students.lengthi++)
    {
    
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 0students.lengthi++)
    {
    
System.out.println(students[i].student_id 
    
students[i].last_name students[i].first_name);
    }
    }



Last edited by ctbalamurali; 10-20-2008 at 07:22 PM..
ctbalamurali is offline   Reply With Quote