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
startDatefield is of typejava.lang.String. At least, the order in the output confirms that. TheString#compareTo()will orderStringvalues 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 useSimpleDateFormat#parse()to convert theStringtoDateinside thecompare()method and then callDate#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.