Sorting date using Comparator.
Hi frnds,
I have a problem sorting a date using comparator Interface. To the compare method I am passing Objects, which contains values retrieved from bean.
I have hyperlinks for all the fields, upon clicking am able to sort all the fields except the date:
The format of date is MM/DD/YYYY. It is sorting only taking month into consideration. I want the date to be sorted completely taking into consideration the complete date.
Kindly help me in this regards.
Below is the code listed:
publicint compare(Object vendoremployee1, Object vendoremployee2){
String strSowTitle1 = ((CVendorEmployees) vendoremployee1).getSowTitle().toUpperCase();
String strSowNum1 = ((CVendorEmployees) vendoremployee1).getSowNumber().toUpperCase();
String lastName1 = ((CVendorEmployees) vendoremployee1).getLastName().toUpperCase();
String strCreatedDate1 = ((CVendorEmployees) vendoremployee1).getCreatedDate().toUpperCase();
String strSowTitle2 = ((CVendorEmployees) vendoremployee2).getSowTitle().toUpperCase();
String strSowNum2 = ((CVendorEmployees) vendoremployee2).getSowNumber().toUpperCase();
String lastName2 = ((CVendorEmployees) vendoremployee2).getLastName().toUpperCase();
String strCreatedDate2 = ((CVendorEmployees) vendoremployee2).getCreatedDate().toUpperCase();
// How do i sort
strCreatedDate1.compareTo(strCreatedDate2);
Thanks
[1571 byte] By [
beejuma] at [2007-11-27 9:45:58]

# 1
II am assuming that you are using either the Collections.sort() method, passing in a Vector of your objects or the Arrays.sort() method passing in an array of your objects. Either way your class definition for your object must implement Comparable. Then you have to implement the compareTo(Object o) method. Inside this method you can setup the sort any way you want. If you want the object to sort by the date member, the easiest way to accomplish the sort is to get the milliseconds from EPOC. Then you can sort either ascending or descending.
Example code: forgive the formatting, cut and paste it into an editor
The example has the data member as a Long object.
Hope this is helpful.
public int compareTo( Object o ) throws ClassCastException
{
YourClassNameHere obj;
if( o instanceof YourClassNameHere)
{
obj = (YourClassNameHere) o;
}
else
{
throw new ClassCastException("Specified Object o is not of type YourClassNameHere." );
}
//Only if these are not primitives
if( this.getYourDatamember() != null && obj.getYourDatamember() != null)
{
if(this. getYourDatamember().longValue() < obj. getYourDatamember().longValue())
{
return -1;
}
else if( this. getYourDatamember().longValue() > obj.getYourDatamember().longValue() )
{
return 1;
}
else
{
return 0;
}
}
else if(this.getYourDatamember != null && obj.getYourDatamember() == null)
{
return -1;
}
else if(this.getYourDatamember == null && obj.getYourDatamember() != null)
{
return 1;
}
else
{
return 0;
}
}