简体   繁体   English

使用compareTo表示年,月和日。Java

[英]Use compareTo for year,month and day.. Java

I wanna sort the dates out on the screen but the thing is, when I use compareTo method, I can only use it with one of the Date attributes: Year, month or day.. not all of them. 我想在屏幕上整理日期,但事实是,当我使用compareTo方法时,只能将其与以下Date属性之一一起使用:Year,month或day ..并非全部。 This is a custom class, not java.util.Date class. 这是一个自定义类,而不是java.util.Date类。

I am required to sort it out on the screen using compareTo method. 我需要使用compareTo方法在屏幕上进行排序。

This is what I have done. 这就是我所做的。

public int compareTo(Date date) {
    if(getYear()-date.getYear()>0 && getMonth()-date.getMonth()>0){

        return 1;
    }
    if(getYear()-date.getYear()<0 && getMonth()-date.getMonth()<0 ){

        return -1;
    }
    return 0;
}

You should only compare the months if the years are equal. 如果年份相等,则只能比较月份。 Similarly, you should only compare the days if the months are equal. 同样,如果两个月相等,则只应比较日期。

public int compareTo(Date date) {
    if(getYear() == date.getYear()) {
        if (getMonth() == date.getMonth()) {
            return getDay() - date.getDay ();
        } else {
            return getMonth() - date.getMonth ();
        }
    } else {
        return getYear() - date.getYear();
    }
}

Note that if for a given property the values of the two Dates are not equal, you can return the difference of those values instead of checking if it's positive or negative and then returning 1 or -1. 请注意,如果对于给定的属性,两个日期的值不相等,则可以返回这些值的差值,而不是检查其值是正还是负,然后返回1或-1。 compareTo is not required to return 1, 0 or -1. compareTo不需要返回1、0或-1。 It can return any int value. 它可以返回任何int值。

Java 8 alleviates some of the boilerplate for sorting by particular fields with Comparator.comparing . Java 8通过Comparator.comparing减轻了按特定字段排序的样板。

dateList.sort(Comparator.comparing(Date::getYear)
                  .thenComparing(Date::getMonth)
                  .thenComparing(Date::getDay));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM