Coinnigh Coinnigh - 2 years ago 74
Java Question

Cannot understand the before function of the Calendar class

I wrote the following code in Eclipse, I think all lines should print

, but only the second line print
, can anyone explain it to me?

Date date = new Date();

Calendar cal = Calendar.getInstance();
cal.add(Calendar.WEEK_OF_YEAR, -1);


Answer Source

This is the code of the function Calendar.before(Object when):

public boolean before(Object when) {
        return when instanceof Calendar
            && compareTo((Calendar)when) < 0;

As you can see, it checks if given object is Calendar, and if it is not, like in your case, it returns false.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download