modifying the after method in calender class to return true when greater than equal to instead of strictly greater

anon0808 :
import java.util.Calendar;
import java.util.Date;

public class exercise4 {
    public static void main (String[] args) throws InterruptedException {
    Calendar cal1 = new CalendarSubclass();
    cal1.setTime(new Date());
    Thread.sleep(1000);
    Calendar cal2 = new CalendarSubclass();
    cal2.setTime(new Date());
    System.out.println(cal2.after(cal1));
    System.out.println(cal1.after(cal2));
    System.out.println(cal1.after(cal1));
    System.out.println(cal2.after(cal2));
    }
}

class CalendarSubclass extends Calendar {
    @Override
    public boolean after(Object when) {
        if (when instanceof Calendar && super.compareTo((Calendar) when) == 0) {
        //if (when instanceof Calendar && ((Calendar) when).toString().equals(this.toString())) {
        //if (when instanceof Calendar && equals((Calendar) when)) {        
        //          System.out.println("lala");
            return true;
        }
        return super.after(when);
    }
@Override
public int compareTo(Calendar anotherCalendar) {
    return compareDays(this.getFirstDayOfWeek(), anotherCalendar.getFirstDayOfWeek());
}

private int compareDays(int currentFirstDayOfWeek, int anotherFirstDayOfWeek) {
    return (currentFirstDayOfWeek > anotherFirstDayOfWeek) ? 1
            : (currentFirstDayOfWeek == anotherFirstDayOfWeek) ? 0 : -1;
}

}

The output is :

false, false, true, true 

but it should be

true, false, true, true 

since I have overrode the after method using CalenderSubclass.

Edit: When I deleted the compareTo and compareDays method it works, but I am only allowed to modify the after method!

Thomas Kläger :

With your update I can see what causes the problem:

The overriden compareTo(Calendar anotherCalendar) is an invalid implementation for the Calendar.compareTo method. The documentation for the Calendar.compareTo() method states:

Compares the time values [..] represented by two Calendar objects.

But the overriding method clearly does something else (it compares the "firstDayOfWeek" field, which only makes sense for Calendar instances configured for different locales.)

If you can: run away and seek shelter from such broken code!


If you can't: reimplement what the original calendars compareTo method does:

@Override
public boolean after(Object when) {
    if (when instanceof Calendar) {
        Calendar other = (Calendar) when;
        return getTimeInMillis() >= other.getTimeInMillis();
    }
    return super.after(when);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=371859&siteId=1