This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Java in General and the fly likes Sorting List By Comparator Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Sorting List By Comparator" Watch "Sorting List By Comparator" New topic
Author

Sorting List By Comparator

nazeer hussain
Greenhorn

Joined: Feb 06, 2006
Posts: 21
Hi

I have a code to sort the object list by a specific attribute as follows.

public GenericComparator(String field, String order) {
super();
this.fieldName=field;
if (order == null || order.equals(ASC)){
this.sortOrder=ASC;
} else if (order.equals(DESC)){
this.sortOrder=DESC;
}

}

public int compare(Object o1, Object o2) {
Object value1;
Object value2;
try{
Field f = this.getAccessibleField(o1);

if (f == null) return 0;

if (this.sortOrder.equals(ASC)){
value1 = f.get(o1);
value2 = f.get(o2);
} else {
value2 = f.get(o1);
value1 = f.get(o2);

}

return this.compareField( value1, value2);
}catch (Exception nsfe){
System.out.println(nsfe);
return 0;
}

}


But I want to sort the objects after calculating a ratio of two different attributes in the objects in object list.

Please give me an idea.

Thanks in advance

Nazeer
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32685
    
    4
You have already had a useful reply on the beginners' forum.

A Comparator doesn't return a ratio, unless you have done lots of arithmetic in it.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Sorting List By Comparator
 
Similar Threads
Please help with sorting multiple columns
Comparator not sorting properly.
Sorting Table Columns
Comparator and Comparable
Collections problem