sorting by date an array of bean having date member

只谈情不闲聊 提交于 2019-12-24 23:24:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!