我试图编写一个简单的程序,通过从最早的日期到最新的排序来排序给定日期的顺序。
我能够按年份对日期进行排序,但是当两个日期有相同的年份,并且我需要按月排序时,就会出现问题。我一直在尝试嵌套if-语句,并尝试实现while循环,但我似乎不能完全正确地实现它。我知道,在我的if语句中,我遗漏了一种语句,它告诉java按month < other.month和day < other.day排序,但我不能完全正确.
目前的投入/产出:
1999年10月5日、1999年5月19日、1999年10月3日、1999年3月19日、2000年5月10日、2000年5月19日、2000年10月3日、2000年3月19日、2000年3月19日
class Date implements Comparable<Date> {
private int year;
private int month;
private int day;
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
@Override
public int compareTo(Date other) {
if(year < other.year) {
return Integer.compare(this.year, other.year);
}
if(year == other.year) {
return Integer.compare(this.month, other.month);
}
if(month == other.month) {
return Integer.compare(this.day, other.day);
}
return day;
}
public String toString() {
return day + "/" + month + " " + year;
}
}发布于 2018-12-03 18:39:36
多年来,您并不是在检查所有的情况,year < other.year应该是year != other.year,另外还有其他一些问题。你想做的是:
if years aren't same
return sort by year
else, if months aren't same
return sort by months
else
return sort by days发布于 2018-12-03 19:08:17
三个字段的编码比较容易出错。为了减少bug的风险,使用comparingInt和thenComparingInt接口的Comparator方法,就像在评论中提到的Aomine:
private static final Comparator<Date> dateComparator
= Comparator.comparingInt((Date d) -> d.year)
.thenComparingInt(d -> d.month)
.thenComparingInt(d -> d.day);
@Override
public int compareTo(Date other) {
return dateComparator.compare(this, other);
}更好的是,为字段提供getter,并使用Date::getYear而不是(Date d) -> d.year,同样用于月和日。
它的优势不在于它更短。最大的好处是很难搞错。
https://stackoverflow.com/questions/53599836
复制相似问题