Coinnigh Coinnigh - 6 months ago 13
Java Question

Cannot understand the before function of the Calendar class

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

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

Date date = new Date();

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

System.out.println(cal.before(date));
System.out.println(cal.getTime().before(date));

Answer

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.