开发者

How to sort a collection by a date field?

I'm trying to sort an album by release date. For some reason I am not getting anywhere:

//sort by release date
Collections.sort(this._items, new Comparator<Album>() {
    public int compare(Album t1, Album t2) {
       开发者_如何学编程 int dateCmp = t2.getStartDate().compareTo(t1.getStartDate());
        Log.i("==Albums==", "dateComp: " + dateCmp);
        return t1.getStartDate().compareTo(t2.getStartDate());
    }            
});

What am I doing wrong?

Here is what I see in the output of Foo Fighters Albums by release date:

name: There Is Nothing Left To Lose | release date: 11/2/1999
name: Greatest Hits | release date: 11/3/2009
name: Skin And Bones | release date: 11/7/2006
name: Foo Fighters | release date: 12/10/2003
name: DOA | release date: 12/13/2005
name: Rope | release date: 3/1/2011
name: The Colour And The Shape | release date: 3/30/2010


It look like that your startDate field is of type java.lang.String. At least, the order in the output confirms that. The String#compareTo() will order String values lexicographically, not by the value it represents in the eye of the beholder.

If you change the incorrect type to be java.util.Date, or use SimpleDateFormat#parse() to convert the String to Date inside the compare() method and then call Date#compareTo() instead, then the ordering will work as expected.

I'd replace it by java.util.Date. Always use the right type for the value it represents.


Here is the full code. The issue was because the start date was of type string.

//sort by release date

Collections.sort(this._items, new Comparator<Album>() {    
                        public int compare(Album t1, Album t2) {

                            int dateCmp = 0;

                             try {  

                                SimpleDateFormat formatter; 
                                Date date1; 
                                Date date2; 
                                formatter = new SimpleDateFormat("dd/mm/yyyy");

                                date1 = (Date)formatter.parse(t1.getStartDate()); 
                                date2 = (Date)formatter.parse(t2.getStartDate()); 

                                dateCmp = (date2).compareTo(date1);

                              } 
                              catch (Exception e)
                              {
                                //Log.i("==Albums==", "album special sort - error" );
                              }

                            //Log.i("==Albums==", "dateComp: " + dateCmp);

                            return dateCmp; 

                        }               
                    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜