问题
i am having a bean class like
public class ItemBean{
String item_id, item_title, image_url, link_url, description, publish_date,
in_app_date, sub_section_id, type, duration, orig_url, sync;
public ItemBean() { .... }
....
....
}
now in activity, i am getting values of itemBeans and making list; to use in comparator. You can see my code;
public void sortDate() {
List<ItemBean> listIB = new ArrayList<ItemBean>();
for(int i=0; i<DispLibActivity.itemListVect.size(); i++)
{
listIB.add(DispLibActivity.itemListVect.get(i));
}
// Sorting Call
Collections.sort(listIB, ItemSimpleListActivity.compareDate);
itemBeans = new ItemBean[listIB.size()];
for (int i=0; i<listIB.size(); i++)
{
itemBeans[i] = listIB.get(i);
System.out.println("Date: "+itemBeans[i].publish_date);
}
}
My Comparator
public static Comparator<ItemBean> compareDate = new Comparator<ItemBean>() {
public int compare(ItemBean one, ItemBean other) {
return one.publish_date.compareTo(other.publish_date);
}
}
But, i am getting sorted collection as following :- Date: 1-1-2009 08:00:00 CST Date: 10-1-2011 08:00:00 CST Date: 10-1-2011 08:00:00 CST Date: 12-2-2010 08:00:00 CST Date: 4-1-2009 08:00:00 CST Date: 4-18-2011 08:00:00 CST Date: 4-6-2010 08:00:00 CST Date: 4-6-2010 08:00:00 CST Date: 9-20-2011 08:00:00 CST Date: 9-20-2011 08:00:00 CST Date: 9-20-2011 08:00:00 CST
Which is not proper sorting order.
Can anyone tell me the alternate ways or what is the bug with this code?
回答1:
You have to compare dates and not strings (publish_date). So in method compare() you parse the String date into a Date object (e.g. via SimpleDateFormat) and compare those two dates via Date.compareTo
来源:https://stackoverflow.com/questions/9912331/sorting-by-date-an-array-of-bean-having-date-member