如何按日期字段对集合进行排序?
我正在尝试按发行日期对专辑进行排序。由于某种原因,我一无所获:
//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());
}
});
我做错了什么?
以下是我在 Foo Fighters 专辑的输出中看到的按发行日期排列的内容:
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来您的
startDate
字段的类型为java.lang.String
。至少,输出中的顺序证实了这一点。String#compareTo()
将按字典顺序对String
值进行排序,而不是按其在观看者眼中所代表的值进行排序。如果将错误的类型更改为
java.lang. util.Date
,或使用SimpleDateFormat#parse()
在compare() 中将
方法,然后调用String
转换为Date
Date#compareTo()
相反,排序将按预期进行。我将其替换为 java.util.Date。始终对其表示的值使用正确的类型。
It look like that your
startDate
field is of typejava.lang.String
. At least, the order in the output confirms that. TheString#compareTo()
will orderString
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 useSimpleDateFormat#parse()
to convert theString
toDate
inside 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.这是完整的代码。问题是因为开始日期是字符串类型。
//按照发布日期排序
Here is the full code. The issue was because the start date was of type string.
//sort by release date