首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用可比接口对日期进行排序。

使用可比接口对日期进行排序。
EN

Stack Overflow用户
提问于 2018-12-03 18:37:52
回答 2查看 294关注 0票数 0

我试图编写一个简单的程序,通过从最早的日期到最新的排序来排序给定日期的顺序。

我能够按年份对日期进行排序,但是当两个日期有相同的年份,并且我需要按月排序时,就会出现问题。我一直在尝试嵌套if-语句,并尝试实现while循环,但我似乎不能完全正确地实现它。我知道,在我的if语句中,我遗漏了一种语句,它告诉java按month < other.monthday < 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日

代码语言:javascript
复制
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;
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-12-03 18:39:36

多年来,您并不是在检查所有的情况,year < other.year应该是year != other.year,另外还有其他一些问题。你想做的是:

代码语言:javascript
复制
if years aren't same
 return sort by year
else, if months aren't same
 return sort by months
else
 return sort by days
票数 3
EN

Stack Overflow用户

发布于 2018-12-03 19:08:17

三个字段的编码比较容易出错。为了减少bug的风险,使用comparingIntthenComparingInt接口的Comparator方法,就像在评论中提到的Aomine:

代码语言:javascript
复制
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,同样用于月和日。

它的优势不在于它更短。最大的好处是很难搞错。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53599836

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档